html 的一部分结构如下。我想从中获得工作“标题”和“时间”。我可以单独获取它们,例如:
from bs4 import BeautifulSoup
pages = '<div class="content"> \
<a href="Org"> \
<h3 class="title"> \
Dep. Manager</h3> \
</a> \
<div class="contributor"></div> \
<p>John</p> \
<time class="time"> \
<span class="timestamp">May 02 2016</span> \
</time> \
</div>'
soup = BeautifulSoup(pages, "lxml")
soup.prettify()
s = soup.find_all(class_ = "title")[0]
t = soup.find_all('span', class_ = "timestamp")[0].text.strip()
pp_title = s.text.strip()
print t
print (pp_title)
它返回我想要的。
Dep. Manager
May 02 2016
对于“时间”,我想要另一种方式来获取它,因为“时间”总是在“标题”下方。我试过这条线来获取“时间”,它不起作用。
print (s.parent.next_sibling.next_sibling)
从关系到“标题”的“时间”的正确方法是什么?谢谢。
最佳答案
您可以通过指定详细信息findParent
:
t = s.findParent("div", class_='content').find('span', class_='timestamp').text.strip()
例子:
titles = soup.find_all(class_="title")
for title in titles:
timestamp = title.findParent("div", class_='content').find('span', class_='timestamp').text.strip()
print(title.text.strip(), timestamp)
关于Python BeautifulSoup 从父/兄弟关系中获取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58679479/