2016-04-11 4 views
0

私はちょうどPythonを学び始め、この問題に直面しました。アマゾンの価格を解析してコンソールに印刷することになりました。ウェブページから情報を解析しようとしているときにHTTPErrorを取得

これは私のコードです:

import requests, bs4 

def getAmazonPrice(productUrl): 
    res = requests.get(productUrl) 
    res.raise_for_status() 

    soup = bs4.BeautifulSoup(res.text, 'html.parser') 
    elems = soup.select('#addToCart > a > h5 > div > div.a-column.a-span7.a-text-right.a-span-last > span.a-size-medium.a-color-price.header-price') 
    return elems[0].text.strip() 


price = getAmazonPrice('http://www.amazon.com/Automate-Boring-Stuff-Python-Programming/dp/1593275994/ref=sr_1_2?ie=UTF8&qid=1460386052&sr=8-2&keywords=python+book') 
print('The price is ' + price) 

エラーメッセージ:

Traceback (most recent call last): File "D:/Code/Python/Basic/webBrowser-Module.py", line 37, in price = getAmazonPrice(' http://www.amazon.com/Automate-Boring-Stuff-Python-Programming/dp/1593275994/ref=sr_1_2?ie=UTF8&qid=1460386052&sr=8-2&keywords=python+book ') File "D:/Code/Python/Basic/webBrowser-Module.py", line 30, in getAmazonPrice res.raise_for_status() File "C:\Python33\lib\requests\models.py", line 844, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 503 Server Error: Service Unavailable for url: http://www.amazon.com/Automate-Boring-Stuff-Python-Programming/dp/1593275994/ref=sr_1_2?ie=UTF8&qid=1460386052&sr=8-2&keywords=python+book

Process finished with exit code 1

答えて

3

User-Agentヘッダを提供することにより、実際のブラウザするふりは、この特定の問題を修正します:

res = requests.get(productUrl, headers={ 
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36" 
}) 

また、CSSを調整する必要がありますセレクタ。たとえば、.header-priceは、ページ上のすべての価格(非プライムとプライム)を取得します。

+0

今、私はこの問題を抱えています。IndexError:リストインデックスが範囲外です。 – Viktor

+0

@Viktorは既に対処済みで、アップデートを確認してください。 – alecxe

+0

ありがとうございました! – Viktor

関連する問題