我正在尝试通过 Transfetmarkt 从各种 html 表格中抓取英国足球统计数据使用 pandas.read_html() 函数的网站。
例子:
import pandas as pd
url = r'http://www.transfermarkt.co.uk/en/premier-league/gegentorminuten/wettbewerb_GB1.html'
df = pd.read_html(url)
但是这段代码会产生一个“ValueError: Invalid URL”错误。
然后我尝试使用 urllib2.urlopen() 函数解析同一个网站。这次我收到“HTTPError:HTTP 错误 404:未找到”。经过通常的反复试验和错误查找后,发现 urllib2 header 向网络服务器提供了一个类似 python 的代理,我认为它无法识别。
现在,如果我修改 urllib2 的代理并使用 beautifulsoup 读取其内容,我就可以毫无问题地读取表格。
例子:
from BeautifulSoup import BeautifulSoup
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
url = r'http://www.transfermarkt.co.uk/en/premier-league/gegentorminuten/wettbewerb_GB1.html'
response = opener.open(url)
html = response.read()
soup = BeautifulSoup(html)
table = soup.find("table")
如何修改 pandas 的 urllib2 header 以允许 python 抓取该网站?
谢谢
最佳答案
目前你不能。相关代码:
if _is_url(io): # io is the url
try:
with urlopen(io) as url:
raw_text = url.read()
except urllib2.URLError:
raise ValueError('Invalid URL: "{0}"'.format(io))
如您所见,它只是将 url
传递给 urlopen
并读取数据。您可以提出问题请求此功能,但我假设您没有时间等待它得到解决,因此我建议使用 BeautifulSoup 来解析 html 数据,然后将其加载到 DataFrame 中。
import urllib2
url = 'http://www.transfermarkt.co.uk/en/premier-league/gegentorminuten/wettbewerb_GB1.html'
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
response = opener.open(url)
tables = pd.read_html(response.read(), attrs={"class":"tabelle_grafik"})[0]
或者如果你可以使用requests
:
tables = pd.read_html(requests.get(url,
headers={'User-agent': 'Mozilla/5.0'}).text,
attrs={"class":"tabelle_grafik"})[0]
关于python - 如何修改 Pandas 的 Read_html 用户代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18939133/