如何提取带有标签的标签内的文本?

时间:2019-10-11 08:19:14

标签: python beautifulsoup

我想使用beautifulsoup解析html页面。我想在标签内部提取文本而不删除内部html标签。例如示例输入:

<a class="fl" href="https://stackoverflow.com/questio...">
    Angular2 <b>Router link not working</b>
</a>

示例输出:

'Angular2 <b>Router link not working</b>'

我已经尝试过了:

from bs4 import Beautifulsoup
string = '<a class="fl" href="https://stackoverflow.com/questio...">
         Angular2 <b>Router link not working</b>
         </a>'
soup = Beautifulsoup(string, 'html.parser')
print(soup.text)

但是它给出了:

'Angular2 Router link not working'

如何在不删除内部标签的情况下提取文本?

3 个答案:

答案 0 :(得分:2)

here开始,第一个答案很好用。对于此示例:

+=

它给出:

from bs4 import Beautifulsoup
string = '<a class="fl" href="https://stackoverflow.com/questio...">
             Angular2 <b>Router link not working</b>
         </a>'
soup = BeautifulSoup(string, 'html.parser')
soup.find('a').encode_contents().decode('utf-8')

答案 1 :(得分:1)

您正在编写print(soup.text)时从标签'a'中提取所有文本,包括其中的每个标签。 如果您只想获取标记“ b”对象,则应尝试以下操作:

soup = BeautifulSoup(string, 'html.parser')
b = soup.find('b')
print(b)
print(type(b))

soup = BeautifulSoup(string, 'html.parser')
b = soup.find('a', class_="fl").find('b')
print(b)
print(type(b))

输出:

  
<b>Router link not working</b>
<class 'bs4.element.Tag'>

如您所见,它将在beautifullsoup对象中返回标签'b'

如果您需要字符串格式的数据,则可以编写:

b = soup.find('a', class_="fl").find('b')
b = str(b)
print(b)
print(type(b))

输出:

  
<b>Router link not working</b>
<class 'str'>

答案 2 :(得分:0)

如Den所言,您需要获取该内部标签,然后将其存储为str类型以包含该内部标签。在Den给出的解决方案中,它将排他性地抓取<b>标签,而不是父标签/文本,如果其中还有其他样式的标签,则不会。但是,如果还有其他标记,则可以更笼统一些,让它找到<a>标记的子元素,而不是专门找到<b>标记。

因此,本质上,这将是找到<a>标记并获取整个文本。然后它将进入该<a>标记的子代中,将其转换为字符串,然后用该字符串(包括标记)替换该父文本中的文本

string = '''<a class="fl" href="https://stackoverflow.com/questio...">
     Angular2 <b>Router link not working</b> and then this is in <i>italics</i> and this is in <b>bold</b>
     </a>'''



from bs4 import BeautifulSoup, Tag

soup = BeautifulSoup(string, 'html.parser')
parsed_soup = ''

for item in soup.find_all('a'):
    if type(item) is Tag and 'a' != item.name:
        continue
    else:
        try:
            parent = item.text.strip()
            child_elements = item.findChildren()
            for child_ele in child_elements:
                child_text = child_ele.text
                child_str = str(child_ele)


                parent = parent.replace(child_text, child_str)
        except:
            parent = item.text

print (parent)

输出:

print (parent)
Angular2 <b>Router link not working</b> and then this is in <i>italics</i> and this is in <b>bold</b>