使用Python爬取2021年财富500强榜单返回空结果问题求助
问题原因
- 目标页面属于前端动态渲染类型,服务器返回的原始HTML仅包含页面框架,你需要的财富500强表格数据是页面加载后由JavaScript异步请求接口生成的
- 你当前用
urlopen请求到的是未经过JS渲染的静态HTML,不存在rt-tbody类的表格元素,所以返回结果为空
适配Google Colab环境的解决方案
方案1:直接调用数据接口(最简便)
无需解析页面,直接调用页面后端的公开数据接口获取结构化数据,直接导出为csv即可:
import requests import pandas as pd api_url = "https://fortune.com/wp-json/fortune/v1/companies/fortune500/2021?limit=500" # 配置请求头避免被拦截 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36" } resp = requests.get(api_url, headers=headers) all_data = resp.json()["data"] # 转换为表格格式保存 df = pd.DataFrame(all_data) df.to_csv("fortune500_2021.csv", index=False, encoding="utf-8-sig")
方案2:模拟浏览器渲染页面(适配原有页面解析逻辑)
如果需要沿用原有BeautifulSoup解析页面的逻辑,可以用Selenium模拟浏览器加载完整渲染后的页面再解析:
# Colab环境先安装依赖 !apt update > /dev/null 2>&1 !apt install chromium-chromedriver > /dev/null 2>&1 !pip install selenium > /dev/null 2>&1 from selenium import webdriver from bs4 import BeautifulSoup import pandas as pd # 配置无头浏览器参数 chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome(options=chrome_options) url = "https://fortune.com/fortune500/2021/search" driver.get(url) # 等待3秒保证页面渲染完成 driver.implicitly_wait(3) # 获取渲染后的完整页面源码 soup = BeautifulSoup(driver.page_source, "html.parser") table_div = soup.find('div', {'class': 'rt-tbody'}) # 后续可自行解析table_div的内容存入DataFrame导出为csv driver.quit()
内容的提问来源于stack exchange,提问作者ai algorithm
相关产品推荐
相关产品推荐

