首页 > 解决方案 > BeautifulSoup find_all 带参数

问题描述

这是我第一次使用 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

标签: pythonbeautifulsoup

解决方案


您的示例代码的问题是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')

推荐阅读