【发布时间】:2020-04-14 06:48:46
【问题描述】:
我正在尝试通过 beautifulsoup 从表中检索数据,但不知何故我的(初学者)语法是错误的:
from bs4 import BeautifulSoup
import requests
main_url = "https://www.apo-in.de/product/acc-akut-600-brausetabletten.24170.html"
req = requests.get(main_url)
soup = BeautifulSoup(req.text, "html.parser")
title = soup.find("div", id = "accordionContent5e95581b6e244")
results = {}
for row in title.findAll('tr'):
aux = row.findAll('td')
results[aux[0].string] = aux[1].string
print(results)
这是相关代码:
<div id="accordionContent5e95581b6e244" class="panel-collapse collapse in">
<div class="panel-body">
<table class="table" width="100%">
<tbody>
<tr>
<th width="170">PZN</th>
<td>00520917</td>
</tr>
<tr>
<th width="170">Anbieter</th>
<td>Hexal AG</td>
</tr>
我的目标是从th td 单元格中检索字典。
beautifulsoup 中如何做到这一点?
【问题讨论】:
-
直到现在。我尝试应用该示例,但确实收到错误: from bs4 import BeautifulSoup ImportError: bad magic number in 'bs4': b'\x03\xf3\r\n'
-
会出现什么问题?我可能会尝试遍历所有 tr 和 td。 for row in title.findAll('tr'): for aux in row.findAll('td'): results[aux[0].string] = aux[1].string 你的 'td' 中是否有多个html?如果不是,为什么要使用“findAll 函数”?
-
每个tr只有一个td。我正常使用scrapy,现在第一次尝试使用BS4,由于执行test.py文件导致上述导入错误,因此无法运行。感谢您帮助我开始这个话题。
-
@merlin 这是一个完全不相关的错误。您的 bs4 安装无法正常工作。见here
标签: python beautifulsoup scrapy