python - Beautiful Soup 没有返回 html 表的列表
问题描述
我正在尝试从下一页的表格中提取描述、日期和网址:
https://www.fda.gov/safety/recalls-market-withdrawals-safety-alerts
为了使我的代码与其他 20 个 url 保持一致,我需要具有以下逻辑,即 findall 的整个正文,然后遍历它以查找适用的数据。
问题是表体为空。
import requests
from bs4 import BeautifulSoup
r = requests.get("https://www.fda.gov/safety/recalls-market-withdrawals-safety-alerts")
c = r.content
soup = BeautifulSoup(c,"html.parser")
all = soup.find_all("tbody") #whole table text THIS IS WHERE THE PROBLEM ORIGINATES
for item in all:
print(item.find_all("tr").text) #test for tr text i.e. product description
print(item.find("a")["href"]) #url
print(item.find_all("td")[0].text) #date (won't work but can't test until tbody returns data
我究竟做错了什么?
提前致谢!
解决方案
该页面中的表格是使用 javascript 从另一个页面动态加载的。使用浏览器中的开发人员工具,您可以复制该请求并将其用于您的代码。然后加载到 pandas 数据框中,你就完成了:
import requests
import pandas as pd
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Language': 'en-US,en;q=0.5',
'X-Requested-With': 'XMLHttpRequest',
'Connection': 'keep-alive',
'Referer': 'https://www.fda.gov/safety/recalls-market-withdrawals-safety-alerts',
'TE': 'Trailers',
}
params = (
('_', '1589124541273'),
)
response = requests.get('https://www.fda.gov/files/api/datatables/static/recalls-market-withdrawals.json', headers=headers, params=params)
response
df = pd.read_json(response.text)
然后使用标准的 pandas 方法,您可以从表中提取目标信息。
在这种特殊情况下,另一种选择是尝试使用 FDA 的 API。
推荐阅读
- python - 在模块的同一子目录中导入文件
- algorithm - 基于可用资源,如何在 Go 中构建依赖图?
- android - 在调试模式下禁用新的 Firebase Crashlytics
- mongodb - MongoDB 未在 docker-compose 上启动
- junit5 - 如何将多个参数传递给@ValueSource
- spring-boot - 从 SCDF 执行任务时,作为部分作业参数公开的数据库凭据
- swiftui - SwiftUI.Font 如何应用 UIFontDescriptor.FeatureKey.featureIdentifier
- node.js - 控制器是在应用层还是基础设施层?我什至应该在 Clean Architecture 中使用控制器吗?
- node.js - 如何将 Mongo 集合中的 2 个字段与数组中的一个字段匹配
- c++ - 如何判断类型双关语在我的平台上是否正常?