【问题标题】:Problems with parsing HTML data in Python在 Python 中解析 HTML 数据的问题
【发布时间】:2021-12-18 07:54:24
【问题描述】:

我试图将 bash 中的一个小脚本迁移到 python。但我不知道如何提出 Curl 请求和 Grep 一些信息。

我已经尝试将 python3 与子进程一起使用,但总是出错,所以我尝试在 python 中使用 BeautifulSoup,但由于响应是 td 中的列表,我不知道如何获取它。

那么有什么方法可以在 python 中发出 curl 请求并使用 grep 和 sed 进行管道传输?

这是 curl 请求。

locations=$(curl -silent https://example.com/location/$stores | grep -P -o 'Location.*?<div class="row">' | sed -e :a -e 's/<[^>]*>//g;/</N;//ba' | sed 's/./& - /12')

这是我的 python3 代码

import requests
import hashlib
from bs4 import BeautifulSoup

store = 'Here Store Name'
url = "https://example.com/?store="+store
session = requests.Session()
request = s.get(url)
soup = BeautifulSoup(request.text, "html.parser")

for grabtg in soup.find_all("td"):
    print(grabtg.contents[0])

我得到的响应是这个,但我唯一需要的是 StoreNames

Store Name
ID
Employes
1
StoreName1
4827489
100
2
StoreName2
4827499
150
3
StoreName3
4827480
220

但是响应是否大于 3 个商店我收到此错误

IndexError: list index out of range

【问题讨论】:

  • 理想情况下是发布您迄今为止在 Python 中尝试过的内容...
  • 实际网址是什么?
  • 我可以建议删除 bash 标记。这个问题似乎与 bash 无关。
  • 如果您只需要商店名称,则不要打印 all 表格单元格。另外,不要假设grabtg.contents 有数据(就像你目前所做的那样),因为很明显,它有时没有。 HTML解析带有很多if检查。
  • @JanWilamowski 问题是所有其他信息都在其他 td 标签内,有没有办法每 x 行选择 td?

标签: python html-parsing


【解决方案1】:

您没有向我们展示实际的 URL 或 HTML,但如果您想选择每行中的第一个单元格,您可以尝试:

for first_cell in soup.find_all("tr td:first-child"):
    if first_cell:
        print(first_cell.contents)

【讨论】:

    猜你喜欢
    • 2011-10-17
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 2015-06-06
    • 2013-04-01
    相关资源
    最近更新 更多