Python BeautifulSoup从父/兄弟关系中获取内容
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python BeautifulSoup从父/兄弟关系中获取内容相关的知识,希望对你有一定的参考价值。
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)
另一答案
我不知道问题出在您提供的字符串中还是其他地方,但是每一次对next_sibling
的调用都会返回u' '
。所以我尝试了这个:
s.parent.next_sibling.next_sibling.next_sibling.next_sibling.next_sibling.next_sibling.findChildren()[0]
我知道很长,但是可以完成工作。
另一答案
您可以将soup.find_all
与re
一起使用:
import re
from bs4 import BeautifulSoup as soup
result = [i.get_text(strip=True) for i in soup(pages, 'html.parser').find_all(re.compile('h3|span'), 'class':re.compile('title|timestamp'))]
输出:
['Dep. Manager', 'May 02 2016']
另一答案
选择共享的父母,然后按班级抓住孩子。假设父母总是两者兼有。您可以根据需要更改选择器以确保同时具有两者。
from bs4 import BeautifulSoup as bs
html = '''
<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 = bs(html, 'lxml')
items = [i.text.strip() for i in soup.select('.content:has(.title) .title, .content:has(.title) .timestamp')]
print(items)
以上是关于Python BeautifulSoup从父/兄弟关系中获取内容的主要内容,如果未能解决你的问题,请参考以下文章
Python selenium —— 父子兄弟相邻节点定位方式详解
Python爬虫:想听榜单歌曲?使用BeautifulSoup库只需要14行代码即可搞定