python - 如何使用 Python 从网页中获取数据
问题描述
去年,我编写了一个 python 脚本,用于存储来自网站的 COVID-19 病例(活跃、治愈和死亡)的数据。该脚本最初运行良好,但后来由于页面上的修改,我只得到了前 2 行,它们现在是标题,没有别的了。早些时候我使用 pandas.read_html() 方法,但它无法获取所有数据。我尝试了以下方法,但这些也无济于事:
- 美丽汤
- lxml.html
也尝试了这里的代码,但仍然是同样的问题。问题的任何原因以及我可以采取的其他一些步骤?
这是我到目前为止所尝试的:
- 使用
pandas
url = "https://www.mohfw.gov.in/"
df_list = pd.read_html(url)
- 使用 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)
自昨天以来的总变化自昨天以来的变化自昨天以来的累计变化自昨天以来的累计变化
- 使用
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 中,我只得到前两行,它们实际上是表中的标题。
解决方案
看起来他们已经注释掉了整张桌子。在我的浏览器上,表格也不可见:
您可以使用 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']
推荐阅读
- excel - 当目标是多个单元格时,IsEmpty 返回 False
- javascript - 如何获取要从请求正文发送的文件作为参数?
- python-3.x - 我无法处理以下 for 循环以从数据框中计算 count()
- derivative - 导数与正规函数的关系
- c++ - 如何从派生类创建小部件(按钮)
- html - 对具有背景颜色的父 div 中的 PNG 图像(透明)进行叠加悬停效果的问题
- javascript - 在 express 中访问控制器的查询结果
- mysql - 如何在连接表上/使用连接表编写条件?
- javascript - V8 Ignition 是否执行 Turbofan 生成的高度优化的机器代码?
- header - 外部头文件 ilcplex\cpxconst.h 导致编译器错误