首页 > 解决方案 > 美丽的汤没有找到基本的 HTML 数据

问题描述

我正在尝试使用 BeautifulSoup 从页面中提取数据。我获得了我的 HTML 数据(类型bs4.element.ResultSet:),它包含多行,如下所示,我想将其编译成一个列表:

<td class="va-infobox-label" colspan="1" style="" title="">Weight</td>

但是当我运行如下所示的一条线时......

labels = soup.find_all("va-infobox-label")

labels = soup.find(colspan="1", style="")

...我收到一个属性错误。或者运行...

labels = soup.find_all("va-infobox-label")

...返回语法错误

find如果不获取包含的所有行,我应该使用什么命令或工具va-infobox-label?我的最终目标是从此 HTML 中获取标签列表,根据我的示例(title="">Weight<),其中一个将是“重量”。

如果您需要复制错误:

import requests
from bs4 import BeautifulSoup

as_val_url = 'https://escapefromtarkov.gamepedia.com/AS_VAL'
as_val_page = requests.get(as_val_url)
as_val_soup = BeautifulSoup(as_val_page.content, 'html.parser')
soup = as_val_soup.find_all(id="va-infobox0-content")

labels = soup.find_all("va-infobox-label")

如果浏览一下 HTML 会对您有所帮助,那么我的 pastebin 中会出现一个公开的“美化”副本。我的例子来自第 36 行。

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


您可以使用soup.select通过 CSS 选择器或soup.find_all如下进行搜索

from bs4 import BeautifulSoup
from io import StringIO

data = '''
<tr>
    <td class="va-infobox-label" colspan="1" style="" title="">Slot</td>
    <td class="va-infobox-spacing-h"></td>
    <td class="va-infobox-content" colspan="1" style="" title="">Primary</td>
</tr>
<tr class="va-infobox-spacing">
    <td class="va-infobox-spacing-v" colspan="3"></td>
</tr>
<tr>
    <td class="va-infobox-label" colspan="1" style="" title="">Weight</td>
    <td class="va-infobox-spacing-h"></td>
    <td class="va-infobox-content" colspan="1" style="" title="">2.587 kg</td>
</tr>
<tr class="va-infobox-spacing">
    <td class="va-infobox-spacing-v" colspan="3"></td>
</tr>
<tr>
    <td class="va-infobox-label" colspan="1" style="" title="">Grid size</td>
    <td class="va-infobox-spacing-h"></td>
    <td class="va-infobox-content" colspan="1" style="" title="">5x2</td>
</tr>
'''

f = StringIO(data)
soup = BeautifulSoup(f, 'html.parser')
for e in soup.find_all('td', {'class': 'va-infobox-label'}):
    print('find_all', e)

for e in soup.select('.va-infobox-label'):
    print('select', e)



推荐阅读