【问题标题】:getting HTTPError while trying to parse info from webpage尝试解析网页信息时出现 HTTPError
【发布时间】:2016-08-01 22:21:13
【问题描述】:

我刚开始学习 Python 就遇到了这个问题。能够从亚马逊解析价格并将其打印到控制台。

这是我的代码:

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(最近一次调用最后一次):文件 “D:/Code/Python/Basic/webBrowser-Module.py”,第 37 行,在 价格 = 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') 文件“D:/Code/Python/Basic/webBrowser-Module.py”,第 30 行,在 获取亚马逊价格 res.raise_for_status() 文件“C:\Python33\lib\requests\models.py”,第 844 行,在 raise_for_status 引发 HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 503 Server Error: Service Unavailable 对于网址: 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

进程以退出代码 1 结束

【问题讨论】:

  • 我收到同样的错误信息。 __requests.exceptions.HTTPError: 503 Server Error: Service Unavailable for url __ 即使按照建议操作

标签: python request beautifulsoup


【解决方案1】:

通过提供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 会为您提供页面上的所有价格(在本例中为非主要价格和主要价格)。

【讨论】:

    猜你喜欢
    • 2011-02-16
    • 2022-12-04
    • 2018-03-06
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多