美丽小组找你所有的争论

2024-06-26 04:52:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次接触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页面示例和我的代码:

^{pr2}$

它什么也不返回,但这是有效的

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

那么它应该什么也不返回吗?或者如何在find_all中输入参数


Tags: datatagtablegroupbuttonallfindtab
2条回答

为什么您要经历这个过程,您只能使用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)

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

示例代码的问题是比较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在评论中指出的那样,使用选择器

^{pr2}$

相关问题 更多 >