python - 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)
我的问题是:
- 如何让 B/S 仅从表格单元格中读取,即不在 HTML 中?
- 如何压缩此列表以删除换行符?
理想情况下,我希望将输出存储为 python 字典
谢谢
解决方案
据我所知,您的方法是正确的,但执行不在那里。为了让它更简单,让我们把它分解成几个小步骤:
获取你要抓取的表
如果是表,则将表的每一行作为列表获取
一旦我们有了行,我们将获取每个单独的单元格并将其放入字典中
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': []}
我希望你明白我做了什么,你可以继续这个并在它之上增加以改进或使其更稳定
推荐阅读
- php - in_array 函数(从文件中读取,而不是在行内)
- ios - Flutter iOS - MediaQuery.of(context).size.width 没有以像素为单位给出宽度
- c - 在 WinAPI 中制作一个无边框可调整大小的窗口
- html - CSS - 调整窗口大小时按钮消失
- python - 如何模拟增量(++)运算符?
- excel - jsreport - 车把 - Xlsx 配方:使用模板时添加图像失败
- arduino - Arduino 没有将完整的 NMEA 语句写入 SD 卡文件
- django - ForeignKey 上等效的 ManyToMany `through Model` 是什么?
- python - 无法将 matplotlib 安装到 pycharm
- reactjs - Redux / 从动作调用调度