2017-07-28 45 views
0

我試圖在使用urllib(刮)它的python中打開一個網頁。該網頁在瀏覽器中看起來很好,但是我得到一個與urlopen 404錯誤。但是,如果查看返回的錯誤文本,它實際上具有完整的網頁。使用urllib 404錯誤,但URL在瀏覽器中正常工作,並在錯誤中返回完整網頁

from urllib.request import Request, urlopen 
    from urllib.error import HTTPError, URLError 
    from bs4 import BeautifulSoup 

    try: 
     html = urlopen('http://www.enduroworldseries.com/series-rankings') 
    except HTTPError as e: 
     err = e.read() 
     code = e.getcode() 
     print(err) 

當我運行代碼,異常被捕獲和「碼」是「404」。如果您在瀏覽器中查看頁面,則err變量具有完整的html。那麼,爲什麼我會得到一個錯誤?

不確定它是否重要,但同一域中的其他頁面可以使用urlopen加載。

+0

該資源 「http://www.enduroworldseries.com/series-rankings」 正在恢復404,當你訪問該網頁的提供者。這可能是阻止人們使用諸如您的代碼訪問/刮取頁面的一種方式。您可能需要考慮正確準備您的用戶代理等等,因此您看起來像從瀏覽器訪問頁面,而不是從代碼訪問頁面。 –

+0

我試着將'User-Agent'設置爲'Mozilla/5.0(Windows NT 10.0; Win64; x64)AppleWebKit/537.36(KHTML,如Gecko)Chrome/59.0.3071.115 Safari/537.36'})。沒有幫助。 –

回答

2

我發現一個解決方案時不知道最初的問題是什麼。簡單地用Requests庫替換urllib。

req = Request('http://www.enduroworldseries.com/series-rankings', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}) 
    html = urlopen(req) 
    bsObj = BeautifulSoup(html, "html.parser") 

成了

response = requests.get('http://www.enduroworldseries.com/series-rankings', {'User-Agent': 'Mozilla/5.0'}) 
    bsObj = BeautifulSoup(response.content, "html.parser") 
相關問題