您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 在bs4.element.ResultSet对象或列表上的beautifulsoup:find_all?

5b51 2022/1/14 8:22:20 python 字数 2267 阅读 649 来源 www.jb51.cc/python

嗨所以我在一个beautifulsoup对象上应用find_all,并找到一些东西,它是一个bs4.element.ResultSet对象或一个列表. 我想在那里进一步做find_all,但是bs4.element.ResultSet对象不允许这样做.我可以循环遍历bs4.element.ResultSet对象的每个元素来执行find_all.但我可以避免循环并将其转换回beautifulsoup

概述

我想在那里进一步做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
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")

总结

以上是编程之家为你收集整理的python – 在bs4.element.ResultSet对象或列表上的beautifulsoup:find_all?全部内容,希望文章能够帮你解决python – 在bs4.element.ResultSet对象或列表上的beautifulsoup:find_all?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶