【问题标题】:How to create dictionary from a table using beautifulsoup?如何使用 Beautifulsoup 从表中创建字典?
【发布时间】: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 中如何做到这一点?

【问题讨论】:

  • 这能回答你的问题吗? BeautifulSoup, a dictionary from an HTML table
  • 直到现在。我尝试应用该示例,但确实收到错误: 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


【解决方案1】:

我建议使用pandas 将数据存储在Data Frame 中,然后导入到dictionary

import pandas as pd
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")
table=soup.select_one(".panel-body >table")
df=pd.read_html(str(table))[0]
print(df.set_index(0).to_dict('dict'))

输出

{1: {'Rezeptpflichtig': 'nein', 'Anbieter': 'Hexal AG', 'PZN': '00520917', 'Darreichungsform': 'Brausetabletten', 'Wirksubstanz': 'Acetylcystein', 'Monopräparat': 'ja', 'Packungsgröße': '40\xa0St', 'Apothekenpflichtig': 'ja', 'Produktname': 'ACC akut 600mg Hustenlöser'}}

【讨论】:

    【解决方案2】:
    1. 第一个错误:您使用的是id,您希望抓取更多页面。
    2. 第二个错误:aux = row.findAll('td') 这将返回一项列表,因为您没有考虑th 标签,这意味着aux[1].string 将引发异常。

    代码如下:

    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", class_="panel-collapse collapse in")
    
    results = {}
    for row in title.findAll('tr'):
        key   = row.find('th')
        value = row.find('td')
        results[key.text] =value.text.strip()
    print(results)
    

    输出:

    {'PZN': '00520917', 'Anbieter': 'Hexal AG', 'Packungsgröße': '40\xa0St', 'Produktname': 'ACC akut 600mg Hustenlöser', 'Darreichungsform': 'Brausetabletten', 'Monopräparat': 'ja', 'Wirksubstanz': 'Acetylcystein', 'Rezeptpflichtig': 'nein', 'Apothekenpflichtig': 'ja'}
    

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 2022-11-18
      • 2014-03-03
      相关资源
      最近更新 更多