繁体   English   中英

BeautifulSoup find_all 带参数

[英]BeautifulSoup find_all with arguments

这是我第一次使用 BeautifulSoup,我不知道我做错了什么

<table class="table sortable table-striped table-condensed r-tab-enabled">
 <thead>
    <tr class="r-tab-buttons r-only-tablet">
       <th class="r-tab-button active" data-defaultsort="disabled" data-group="1">Picks</th>
       <th class="r-tab-button" data-defaultsort="disabled" data-group="2">Bans</th>
       <th class="r-tab-button" data-defaultsort="disabled" data-group="3">Combined</th>
    </tr>

这是我正在使用的 HTML 页面示例和我的代码:

r = requests.get(URL, headers=headers)
soup = bs4.BeautifulSoup(r.text, 'lxml')

table = soup.find_all(lambda tag: tag.name=='table' and tag.has_attr('class') and tag['class'] =="table sortable table-striped table-condensed r-tab-enabled")

它什么都不返回,但这有效

table = soup.find_all(lambda tag: tag.name=='table' and tag.has_attr('class'))

那么它应该什么都不返回吗? 或者我如何将参数输入到find_all

您的示例代码的问题是将tag['class']与字符串值"table sortable table-striped table-condensed r-tab-enabled"tag['class']是一个数组。

要修复您的代码,请将tag['class']与数组进行比较

table = soup.find_all(lambda tag: tag.name=='table' and tag.has_attr('class') and tag['class'] == ["table", "sortable", "table-striped", "table-condensed", "r-tab-enabled"])

或者正如@Jon 在评论中指出的那样,改用选择器

table = soup.select('table.table.sortable.table-striped.table-condensed')

你为什么要经历这个过程,你只能使用find_all('table', class_='classes string')并且你从 html 文件中获取所有表

text = """
    <table class="table sortable table-striped table-condensed r-tab-enabled">
 <thead>
    <tr class="r-tab-buttons r-only-tablet">
       <th class="r-tab-button active" data-defaultsort="disabled" data-group="1">Picks</th>
       <th class="r-tab-button" data-defaultsort="disabled" data-group="2">Bans</th>
       <th class="r-tab-button" data-defaultsort="disabled" data-group="3">Combined</th>
    </tr>
"""

soup = bs4.BeautifulSoup(text, 'html.parser')

for i in soup.find_all('table', class_="table sortable table-striped table-condensed r-tab-enabled"):
    print(i)

你得到了你的信息,可能会有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM