【问题标题】:Python request to crawl URL returns 404 Error while working inside the browser在浏览器中工作时,爬取 URL 的 Python 请求返回 404 错误
【发布时间】:2020-04-01 20:03:51
【问题描述】:

我有一个挂在 url 上的爬虫 python 脚本:pulsepoint.com/sellers.json

机器人使用标准请求来获取内容,但返回错误 404。在浏览器中它可以工作(有 301 重定向,但请求可以跟随)。我的第一个预感是这可能是请求标头问题,所以我复制了我的浏览器配置。代码是这样的

        crawled_url="pulsepoint.com"
        seller_json_url = 'http://{thehost}/sellers.json'.format(thehost=crawled_url)
        print(seller_json_url)
        myheaders = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Language': 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3',
                'Accept-Encoding': 'gzip, deflate, br',
                'Connection': 'keep-alive',
                'Pragma': 'no-cache',
                'Cache-Control': 'no-cache'
            }
        r = requests.get(seller_json_url, headers=myheaders)
        logging.info("  %d" % r.status_code)

但我仍然收到 404 错误。

我的下一个猜测:

  • 登录?此处未使用
  • 饼干?不是我能看到的

那么他们的服务器如何阻止我的机器人?这是一个应该顺便爬的url,没有什么违法的..

提前致谢!

【问题讨论】:

    标签: python request web-crawler robot


    【解决方案1】:

    您还可以解决 SSL 证书错误,如下所示:

    from urllib.request import urlopen
    import ssl
    import json
    
    #this is a workaround on the SSL error
    ssl._create_default_https_context = ssl._create_unverified_context
    crawled_url="pulsepoint.com"
    seller_json_url = 'http://{thehost}/sellers.json'.format(thehost=crawled_url)
    print(seller_json_url)
    
    response = urlopen(seller_json_url).read() 
    # print in dictionary format
    print(json.loads(response)) 
    

    示例响应:

    {'contact_email': 'PublisherSupport@pulsepoint.com', 'contact_address': '360 Madison Ave, 14th Floor, NY, NY, 10017', 'version': '1.0', 'identifiers': [{' name': 'TAG-ID', 'value': '89ff185a4c4e857c'}], 'sellers': [{'seller_id': '508738', ...

    ...'seller_type': 'PUBLISHER'}, {'seller_id': '562225', 'name': 'EL DIARIO', 'domain': 'impremedia.com', 'seller_type': 'PUBLISHER' }]}

    【讨论】:

    • 感谢您的回答!您的代码有效,但需要有重定向的 URL,而不是原始 URL。我有一些带有重定向的 URL 可以正常工作,我不明白为什么这个需要对另一个域进行硬编码..
    • 很抱歉使用了重定向的 url。我更新了我的答案。
    • 感谢您的成功!由于我在 url 中对标题的尊重程度不同,我不得不在解决方案上做一些工作,但你的答案是正确的。我会添加一个作为补充!
    【解决方案2】:

    你可以直接去链接提取数据,不需要301到正确的链接

    import requests
    headers = {"Upgrade-Insecure-Requests": "1"}
    response = requests.get(
        url="https://projects.contextweb.com/sellersjson/sellers.json",
        headers=headers,
        verify=False,
    )
    
    

    【讨论】:

    • 感谢您的建议,但我有几百个 url,有些注册了 Sellers.json,有些没有,还有一些正在使用重定向。所以我想要一个适合大多数情况的健壮爬虫..
    【解决方案3】:

    好吧,只是为了其他人,一个强化版 âńōŋŷXmoůŜ 的答案,因为:

    • 有些网站希望标题回答;
    • 有些网站使用了奇怪的编码
    • 某些网站在未请求时会发送 gzip 后的答案。
        import urllib
        import ssl
        import json
        from io import BytesIO
        import gzip
    
        ssl._create_default_https_context = ssl._create_unverified_context
        crawled_url="pulsepoint.com"
        seller_json_url = 'http://{thehost}/sellers.json'.format(thehost=crawled_url)
        req = urllib.request.Request(seller_json_url)
        # ADDING THE HEADERS
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0')
        req.add_header('Accept','application/json,text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8')
    
        response = urllib.request.urlopen(req)
        data=response.read()
        # IN CASE THE ANSWER IS GZIPPED
        if response.info().get('Content-Encoding') == 'gzip':
            buf = BytesIO(data)
            f = gzip.GzipFile(fileobj=buf)
            data = f.read()
        # ADAPTS THE ENCODING TO THE ANSWER
        print(json.loads(data.decode(response.info().get_param('charset') or 'utf-8')))
    

    再次感谢!

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 2020-12-18
      • 2014-03-15
      • 2019-02-07
      • 1970-01-01
      相关资源
      最近更新 更多