我想提取内容Hello world。请注意,页面上还有多个<table>和类似的<td colspan="2">:
<table border="0" cellspacing="2" width="800">
<tr>
<td colspan="2"><b>Name: </b>Hello world</td>
</tr>
<tr>
...我尝试了以下几种方法:
hello = soup.find(text='Name: ')
hello.findPreviousSiblings但它没有返回任何内容。
此外,我在以下提取My home address时也遇到了问题
<td><b>Address:</b></td>
<td>My home address</td>我也使用相同的方法来搜索text="Address: ",但是如何导航到下一行并提取<td>的内容呢
发布于 2013-01-10 02:21:06
contents运算符可以很好地从<tag>text</tag>中提取text。
<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:发布于 2011-05-14 10:26:53
改用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允许您按照文档元素被解析器处理的顺序在文档元素中移动,而同级方法使用解析树
发布于 2020-11-27 08:51:08
使用以下代码通过python beautifulSoup从html标记中获取提取文本和内容
s = '<td>Example information</td>' # your raw html
soup = BeautifulSoup(s) #parse html with BeautifulSoup
td = soup.find('td') #tag of interest <td>Example information</td>
td.text #Example information # clean text from htmlhttps://stackoverflow.com/questions/5999407
复制相似问题