Beautifulsoup =提取标签内的内容

时间:2011-05-14 02:15:56

标签: python beautifulsoup

我想提取内容“Hello world”。请注意,页面上也有多个<table>和类似的<td colspan="2">

我尝试了以下内容:

hello = soup.find(text='Name: ')
hello.findPreviousSiblings

但它没有任何回报。

以下是代码片段:

<table border="0" cellspacing="2" width="800">
<tr> 
<td colspan="2"><b>Name: </b>Hello world</td>
</tr>
<tr>

此外,我也遇到以下提取“我的家庭住址”的问题:

<td><b>Address:</b></td>

<td>My home address</td>

我也使用相同的方法搜索text =“地址:”但是如何向下导航到下一行并提取<td>的内容?

4 个答案:

答案 0 :(得分:20)

contents运算符适用于从text中提取<tag>text</tag>


<td>My home address</td>示例:

s = '<td>My home address</td>'
soup =  BeautifulSoup(s)
td = soup.find('td') #<td>My home address</td>
td.contents #My home address

<td><b>Address:</b></td>示例:

s = '<td><b>Address:</b></td>'
soup =  BeautifulSoup(s)
td = soup.find('td').find('b') #<b>Address:</b>
td.contents #Address:

答案 1 :(得分:14)

使用next而不是

>>> s = '<table border="0" cellspacing="2" width="800"><tr><td colspan="2"><b>Name: </b>Hello world</td></tr><tr>'
>>> soup = BeautifulSoup(s)
>>> hello = soup.find(text='Name: ')
>>> hello.next
u'Hello world'

next previous 允许您按照解析器处理它们的顺序浏览文档元素,同时兄弟方法使用解析树

答案 2 :(得分:0)

使用以下代码使用python beautifulSoup从html标签中提取文本和内容

s = '<td>Example information</td>'
soup =  BeautifulSoup(s)
td = soup.find('td') #<td>Example information</td>
td.text #Example information

答案 3 :(得分:0)

from bs4 import BeautifulSoup, Tag

def get_tag_html(tag: Tag):
    return ''.join([i.decode() if type(i) is Tag else i for i in tag.contents])