【发布时间】:2020-03-18 19:16:44
【问题描述】:
我想从 CDC 网站 (https://www.cdc.gov/coronavirus/2019-ncov/index.html) 上抓取与 COVID-19 相关的州级信息表。使用 BeautifulSoup 时,当我开始尝试从表中提取任何信息时遇到错误。任何帮助将不胜感激!
import pandas as pd
import requests
from bs4 import BeautifulSoup
from lxml import html
url = 'https://www.cdc.gov/coronavirus/2019-ncov/index.html'
html_content = requests.get(url).text
soup = BeautifulSoup(html_content, "lxml")
gdp_table = soup.find("table", attrs={"class": "ReactTable"})
gdp_table_data = gdp_table.tbody.find_all("div") # contains 2 rows
# Get all the headings of Lists
headings = []
for td in gdp_table_data[0].find_all("td"):
# remove any newlines and extra spaces from left and right
headings.append(td.b.text.replace('\n', ' ').strip())
print(headings)
如果您很难找到我所引用的表格,它位于网页的一半,位于美国地图下方。标题为“States”的地方点击旁边的“+”。
【问题讨论】:
-
首先,您能否发布您遇到的实际错误?您尝试从中删除的元素是一个反应元素,它仅在页面加载时生成内容。你在这里有三个选择:要么使用像 selenium 这样的客户端,硬编码一些 js 来呈现元素,或者像@Dan-Dev 建议的那样获取源 csv。最简单的显然是第三个
-
什么错误,你的问题是什么?
-
大家好!第一次使用,我该如何发布我的错误?或者发布错误的最佳做法是什么。感谢您的耐心等待。
标签: javascript python selenium web-scraping beautifulsoup