python - 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
解决方案
您的示例代码的问题是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')
推荐阅读
- regex - 多列的 ProxySQL 数据屏蔽
- ssl - 获取许多 CNAME 的 SSL 证书?
- c# - 更改 linerenderer 中每个元素的颜色不起作用
- reactjs - React Routes 重定向到 Auth 链接的外部 URL
- java - 尝试在单独的行上打印字符串
- ajax - 构建一个基于 AJAX 的 wordpress 插件
- java - 如何在java中创建一个带有节点的通用类型的get方法
- reactjs - 在 React 中仅渲染下一个未填充的表单组件
- python - 在Python中计算日期之间的天数?
- datetime - 如何将 chrono DateTime 设置为特定的日期和时间?