2013-09-22 35 views
1

我想通過使用pandas.read_html()函數從各個html表通過Transfetmarkt網站刮英語足球統計。如何修改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異常:無效URL」錯誤。

然後我嘗試使用urllib2.urlopen()函數解析同一個網站。這次我得到了一個「HTTPError:HTTP Error 404:Not Found」。在通常的試錯錯誤發現之後,它發現urllib2頭文件向web服務器呈現了一個類似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") 

如何修改熊貓的urllib2的頭,讓蟒蛇湊這個網站?

謝謝

+0

你可能想提出了一個問題,在GitHub上。我很高興看一看(我寫了'read_html') –

+0

done - https://github.com/pydata/pandas/issues/4927 – kbgo

回答

4

目前你不能。相關的代碼:

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)) 

正如你看到的,它只是傳遞urlurlopen並讀取數據。您可以提出請求此功能的問題,但我認爲您沒有時間等待它解決,因此我建議使用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] 
+0

我對那個評論我有點慚愧, ..Captain明顯:| –

+0

+1由於「和平的代碼」....喜歡安心:) –

+0

@PhillipCloud我把那裏的評論,以澄清'io'是什麼:) –