python - 美丽的汤没有找到基本的 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 行。
解决方案
您可以使用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)
推荐阅读
- python - 我们可以使用 tensorflow 用新数据训练预训练模型吗?
- delphi - 使用 TIDSmtp 发送时 HELO 名称无效
- css - 自动完成下拉菜单不显示数据
- python - 当一个句子和一个词被传递时,Python函数将一个词从一个句子变为大写
- python - '_csv.writer' 对象不可迭代。如何追加到csv文件
- terraform - 资源定义语法中的 Terraform 列表令人头疼
- swift - Cocoaasyncsocket 问题,GCDAsyncSocket 连接问题
- python - Python将变量分配给MYSQL查询的正确方法?
- c# - 设置中的 FilePath 定位器?
- powershell - 哈希表中的解释点