Beautifulsoup - nextSibling

rea*_*ady 36 python beautifulsoup

我正在尝试使用以下内容获取内容"我的家庭地址",但得到了AttributeError:

address = soup.find(text="Address:")
print address.nextSibling
Run Code Online (Sandbox Code Playgroud)

这是我的HTML:

<td><b>Address:</b></td>
<td>My home address</td>
Run Code Online (Sandbox Code Playgroud)

导航td标记和拉取内容的好方法是什么?

Hen*_*nry 76

问题是你找到了一个NavigableString,而不是<td>.也nextSibling将寻找下一个NavigableString 或者 Tag所以即使你有<td>它不会工作,你期望的方式.

这就是你想要的:

address = soup.find(text="Address:")
b_tag = address.parent
td_tag = b_tag.parent
next_td_tag = td_tag.findNext('td')
print next_td_tag.contents[0]
Run Code Online (Sandbox Code Playgroud)

或者更简洁:

print soup.find(text="Address:").parent.parent.findNext('td').contents[0]
Run Code Online (Sandbox Code Playgroud)

其实你可以做到

print soup.find(text="Address:").findNext('td').contents[0]
Run Code Online (Sandbox Code Playgroud)

因为findNext只是next一遍又一遍地调用,并且重复解析next下一个元素,直到它匹配为止.


Vya*_*hez 10

如果您使用bs4,请尝试此操作:

print soup.find(string="Address:").find_next('td').contents[0]
Run Code Online (Sandbox Code Playgroud)


dis*_*ame 6

我不知道这在 2011 年是否可行,但在 2021 年,我建议您使用find_next_sibling()以下方法进行操作:

address = soup.find(text="Address:")
b = address.parent
address_td = b.parent
target_td = address_td.find_next_sibling('td')
Run Code Online (Sandbox Code Playgroud)

接受的答案适用于您的情况,但如果您有以下情况则无效:

<div>
  <div><b>Address:</b><div>THE PROBLEM</div></div>
  <div>target</div>
</div>
Run Code Online (Sandbox Code Playgroud)

你最终会得到<div>THE PROBLEM</div>而不是<div>target</div>.