【问题标题】:Request.get timeoutRequest.get 超时
【发布时间】:2020-03-05 13:53:10
【问题描述】:

我想借助 Requests 函数获取网站的 HTML。

我的代码:

import Requests
res = Requests.get('https://store.hp.com/us/en/pdp/hp-laserjet-pro-m404n?jumpid=ma_weekly-deals_product-tile_printers_3_w1a52a_hp-laserjet-pro-m404')

print(res.text)

代码卡在 res。如果您要将 http 替换为: 'http://www.newegg.com/Product/ProductList.aspx?Submit=ENE&N=-1&IsNodeId=1&Description=GTX&bop=And&Page=1&PageSize=36&order=BESTMATCH' - 一切正常。

我如何将任何给定页面的 html 保存到变量中?

【问题讨论】:

  • 您的问题标题和问题正文不一致。您在标题中说request.get timeout,但您的问题只是说“代码卡住”。在你的问题结束时,你会问别的问题。最好编辑您的问题,以便其他人可以更好地帮助您。如果有任何错误,您也应该粘贴错误消息。

标签: python html web-scraping error-handling python-requests


【解决方案1】:

嗯,您正在处理HP 网站,该网站肯定使用了现代网络技术。

这里的问题是您在没有有效的User-Agent 的情况下制作request,这将导致websitefirewall 阻止request 并将其列为bot

这就是你得到错误的原因# 10060 Details

在这里您可以创建一个有效的request 并将HTML 源存储为variable

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0'}

r = requests.get(
    "https://store.hp.com/us/en/pdp/hp-laserjet-pro-m404n?jumpid=ma_weekly-deals_product-tile_printers_3_w1a52a_hp-laserjet-pro-m404", headers=headers)

print(r)

html = r.text # now it's stored

【讨论】:

    【解决方案2】:

    这个网站看起来好像实现了一些基本的反抓取方法。如果请求在浏览器中有效,但在您的代码中无效,您只需要调整请求、标头、cookie 等,直到它更接近浏览器所做的。值得庆幸的是,这个很容易使用。确保您提供用户代理 :)

    res = requests.get('https://store.hp.com/us/en/pdp/hp-laserjet-pro-m404n?jumpid=ma_weekly-deals_product-tile_printers_3_w1a52a_hp-laserjet-pro-m404',
                   headers={'user-agent':'my app'})
    

    【讨论】:

      猜你喜欢
      • 2020-04-04
      • 2018-08-15
      • 2019-10-31
      • 2018-03-11
      • 2020-09-15
      • 2013-10-15
      • 2016-09-10
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多