关于用python制作漂亮汤的问题
我有类似HTML的
<div class="content">Somedata</div>
<div class="content">Somedata</div>
<div class="content">Qualification</div>
<div class="content">THE DATA I WANT</div>
<div class="content">Somedata</div>
<div class="content">Somedata</div>
相同的div标签再次重复
在这种情况下: 不,我或任何唯一标签都包含---仅div标签---
我如何获得资格后的“我想要的数据”文本 预先感谢
答案 0 :(得分:1)
txt = '''
<div class="content">Somedata</div>
<div class="content">Somedata</div>
<div class="content">Qualification</div>
<div class="content">THE DATA I WANT</div>
<div class="content">Somedata</div>
<div class="content">Somedata</div>'''
soup = BeautifulSoup(txt, 'html.parser')
print(soup.select_one('div:contains("Qualification") ~ div').text)
打印:
THE DATA I WANT
或者:
print(soup.find(text="Qualification").find_next().text)
或者:
print(soup.find(lambda t: t.find_previous() and t.find_previous().text == 'Qualification').text)
编辑:要遍历<div>
,可以使用简单的for循环:
for item in souped.find_all(lambda t: t.name == 'div' and t.text == 'Qualification'):
print(item.find_next().text)
答案 1 :(得分:0)
您可以尝试:
from bs4 import BeautifulSoup
html_doc ='''<div class="content">Somedata</div>
<div class="content">Somedata</div>
<div class="content">Qualification</div>
<div class="content">THE DATA I WANT</div>
<div class="content">Somedata</div>
<div class="content">Somedata</div>'''
soup = BeautifulSoup(html_doc, 'lxml')
result = soup.find_all("div", class_="content")[3].text
print(result)
输出将是:
THE DATA I WANT
OR
import re
soup = BeautifulSoup(html_doc, 'lxml')
print(soup.find(text=re.compile('^THE DATA I WANT$')))
OR
print(soup.find(string="Qualification").find_next().text)