首页 > 解决方案 > 如何使用 Python 从网页中获取数据

问题描述

去年,我编写了一个 python 脚本,用于存储来自网站的 COVID-19 病例(活跃、治愈和死亡)的数据。该脚本最初运行良好,但后来由于页面上的修改,我只得到了前 2 行,它们现在是标题,没有别的了。早些时候我使用 pandas.read_html() 方法,但它无法获取所有数据。我尝试了以下方法,但这些也无济于事:

  1. 美丽汤
  2. lxml.html

也尝试了这里的代码,但仍然是同样的问题。问题的任何原因以及我可以采取的其他一些步骤?

这是我到目前为止所尝试的:

  1. 使用pandas

url = "https://www.mohfw.gov.in/"

df_list = pd.read_html(url)

  1. 使用 lmxl.html

>>> import requests
>>> page = requests.get(url)
>>> import lxml.html as lh
>>> doc = lh.fromstring(page.content)
>>> tbody_elements = doc.xpath('//tbody') # table is under `<tbody>` tag but it's able to get the data
>>> tbody_elements
[] # null here
>>> tr_elements = doc.xpath('//tr')
>>> tr_elements
[<Element tr at 0x7fb3f507d260>, <Element tr at 0x7fb3f507d2b8>, <Element tr at 0x7fb3f507d310>]
>>> len(tr_elements)
3
>>>for i in tr_elements:
...     print("Row - ", r)
...     for row in i:
...             print(row.text_content())
...     r=r+1
... 

输出:

('行-', 1)

COVID-19 印度截至时间:2021 年 3 月 14 日 08:00 IST (GMT+5:30) [↑↓ 昨天以来的状态变化]

('行-', 2)

S. No. 州名/UT 活跃病例* 治愈/出院/迁移* 死亡人数**

('行-',3)

自昨天以来的总变化自昨天以来的变化自昨天以来的累计变化自昨天以来的累计变化

  1. 使用BeautifulSoup
>>> from bs4 import BeautifulSoup
>>> url = 'https://www.mohfw.gov.in/'
>>> web_content = requests.get(url).content
>>> soup = BeautifulSoup(web_content, "html.parser")
>>> all_rows = soup.find_all('tr')
>>> all_rows
[<tr><h5>COVID-19 INDIA <span>as on : 15 March 2021, 08:00 IST (GMT+5:30)\t[\u2191\u2193 Status change since yesterday]</span></h5></tr>, <tr class="row1">\n<th rowspan="2" style="width:5%;"><strong>S. No.</strong></th>\n<th rowspan="2" style="width:24%;"><strong>Name of State / UT</strong></th>\n<th colspan="2" style="text-align:center;width:24%;"><strong>Active Cases*</strong></th>\n<th colspan="2" style="text-align:center;width:24%;"><strong>Cured/Discharged/Migrated*</strong></th>\n<th colspan="2" style="text-align:center;width:24%;"><strong>Deaths**</strong></th>\n</tr>, <tr class="row2"><th style="width: 12%;">Total</th><th style="width: 12%;"><span class="mob-hide">Change since yesterday</span><span class="mob-show">Change since<br/> yesterday</span></th>\n<th style="width: 12%;">Cumulative</th><th style="width: 12%;">Change since yesterday</th>\n<th style="width: 12%;">Cumulative</th><th style="width: 12%;">Change since yesterday</th></tr>]
>>> len(all_rows)
3 

在 BeautifulSoup 和 lmxl.html 中,我只得到前两行,它们实际上是表中的标题。

在此处输入图像描述

标签: pythonweb-scrapingbeautifulsouplxml.html

解决方案


看起来他们已经注释掉了整张桌子。在我的浏览器上,表格也不可见:

html源码

您可以使用 BeautifulSoup 找到评论条目并将其解码为更多汤,例如:

from bs4 import BeautifulSoup, Comment
import requests

url = 'https://www.mohfw.gov.in/'
req = requests.get(url)
soup = BeautifulSoup(req.content, "html.parser")
trs = soup.find_all('tr')
comment = trs[-1].find_next(string=lambda text: isinstance(text, Comment))
table_soup = BeautifulSoup(comment, "html.parser")

for tr in table_soup.find_all('tr'):
    print([td.text for td in tr.find_all('td')])

这会给你输出开始:

['1', 'Andaman and Nicobar Islands', '47', '133', '0']
['2', 'Andhra Pradesh', '18159', '19393', '492']
['3', 'Arunachal Pradesh', '387', '153', '3']
['4', 'Assam', '6818', '12888', '48']
['5', 'Bihar', '7549', '14018', '197']
['6', 'Chandigarh', '164', '476', '11']
['7', 'Chhattisgarh', '1260', '3451', '21']
['8', 'Dadra and Nagar Haveli and Daman and Diu', '179', '371', '2']
['9', 'Delhi', '17407', '97693', '3545']
['10', 'Goa', '1272', '1817', '19']

推荐阅读