首页 > 解决方案 > Python BeautifulSoup 仅从表格单元格打印

问题描述

我是美丽汤的新手。我正在尝试获取一个可以抓取网页的 python 脚本,然后打印一个精简列表。到目前为止,我有:

from bs4 import BeautifulSoup
import requests

URL = 'https://shropshire.gov.uk/waste/binday/index.jsc?p=0&go=Go&designation=3&postcode=sy3+9jt&gobutton=Go'
content = requests.get(URL)

soup = BeautifulSoup(content.text, 'html.parser')

current = soup.find("div", {"class": "maxi calendar_month"})

print(current.text)

我的问题是:

  1. 如何让 B/S 仅从表格单元格中读取,即不在 HTML 中?
  2. 如何压缩此列表以删除换行符?

理想情况下,我希望将输出存储为 python 字典

谢谢

标签: pythonbeautifulsoup

解决方案


据我所知,您的方法是正确的,但执行不在那里。为了让它更简单,让我们把它分解成几个小步骤:

  1. 获取你要抓取的表

  2. 如果是表,则将表的每一行作为列表获取

  3. 一旦我们有了行,我们将获取每个单独的单元格并将其放入字典中

    from bs4 import BeautifulSoup
    import requests
    
    main_data = {}
    URL = 'https://shropshire.gov.uk/waste/binday/index.jsc?p=0&go=Go&designation=3&postcode=sy3+9jt&gobutton=Go'
    content = requests.get(URL)
    
    soup = BeautifulSoup(content.text, 'html.parser')
    
    table = soup.find("table")
    rows = table.find_all("tr", {"class": ""})
    
    for row in rows:
        data_list = row.find_all("td")
        for data in data_list:
            is_valid = data.find("div")
            if is_valid:
                tags = [tag.text.strip() for tag in data.find_all("span")]
                date = data.find("div").text.strip()
                main_data[date] = tags
    
    print(main_data)
    

输出:

{'1': [], '2': [], '3': [], '4': ['Rubbish'], '5': [], '6': [], '7': [], '8': [], '9': [], '10': [], '11': ['Garden waste', 'Recycling boxes'], '12': [], '13': [], '14': [], '15': [], '16': [], '17': [], '18': ['Rubbish'], '19': [], '20': [], '21': [], '22': [], '23': [], '24': [], '25': ['Garden waste', 'Recycling boxes'], '26': [], '27': [], '28': [], '29': [], '30': []}

我希望你明白我做了什么,你可以继续这个并在它之上增加以改进或使其更稳定


推荐阅读