python – 在bs4.element.ResultSet对象或列表上的beautifulsoup:find_all
发布时间:2020-05-23 09:43:19 所属栏目:Python 来源:互联网
导读:嗨所以我在一个beautifulsoup对象上应用find_all,并找到一些东西,它是一个bs4.element.ResultSet对象或一个列表. 我想在那里进一步做find_all,但是bs4.element.ResultSet对象不允许这样做.我可以循环遍历bs4.element.ResultSet对象的每个元素来执行find_all.
|
嗨所以我在一个beautifulsoup对象上应用find_all,并找到一些东西,它是一个bs4.element.ResultSet对象或一个列表. 我想在那里进一步做find_all,但是bs4.element.ResultSet对象不允许这样做.我可以循环遍历bs4.element.ResultSet对象的每个元素来执行find_all.但我可以避免循环并将其转换回beautifulsoup对象吗? 请参阅代码了解详情.谢谢 html_1 = """
<table>
<thead>
<tr class="myClass">
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
</table>
"""
soup = BeautifulSoup(html_1,'html.parser')
type(soup) #bs4.BeautifulSoup
# do find_all on beautifulsoup object
th_all = soup.find_all('th')
# the result is of type bs4.element.ResultSet or similarly list
type(th_all) #bs4.element.ResultSet
type(th_all[0:1]) #list
# now I want to further do find_all
th_all.find_all(text='A') #not work
# can I avoid this need of loop?
for th in th_all:
th.find_all(text='A') #works
解决方法ResultSet类是列表的子类,而不是定义了find *方法的Tag class.循环遍历find_all()的结果是最常用的方法:
th_all = soup.find_all('th')
result = []
for th in th_all:
result.extend(th.find_all(text='A'))
通常,CSS selectors可以帮助您一次性解决它,除了不能使用select()方法使用find_all()执行所有操作.例如,bs4 CSS选择器中没有“文本”搜索.但是,例如,如果您必须在元素内找到所有b元素,那么您可以: soup.select("th td") (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
