【问题标题】:How do I convert Python crawled Bing web page content to human-readable?如何将 Python 爬取的 Bing 网页内容转换为人类可读的内容?
【发布时间】:2021-11-06 20:41:23
【问题描述】:

我正在使用 python 爬行 Bing 网页搜索页面。 我发现收到的原始内容看起来像字节类型,但尝试解压缩它失败了。 有人知道这是什么类型的数据,我应该如何从这些原始内容中提取可读性?谢谢!

我的代码显示了原始内容,然后尝试执行 gunzip,因此您可以看到原始内容以及解压缩时的错误。 由于原始内容太长,我只是将前几行粘贴在下面。

代码:

import urllib.request as Request
import gzip

req = Request.Request('www.bing.com')
req.add_header('upgrade-insecure-requests', 1)
res = Request.urlopen(req).read()
print("RAW Content: %s" %ResPage) # show raw content of web
print("Try decompression:")
print(gzip.decompress(ResPage))   # try decompression

结果:

RAW Content: b'+p\xe70\x0bi{)\xee!\xea\x88\x9c\xd4z\x00Tgb\x8c\x1b\xfa\xe3\xd7\x9f\x7f\x7f\x1d8\xb8\xfeaZ\xb6\xe3z\xbe\'\x7fj\xfd\xff+\x1f\xff\x1a\xbc\xc5N\x00\xab\x00\xa6l\xb2\xc5N\xb2\xdek\xb9V5\x02\t\xd0D \x1d\x92m%\x0c#\xb9>\xfbN\xd7\xa7\x9d\xa5\xa8\x926\xf0\xcc\'\x13\x97\x01/-\x03... ...

Try decompression:
Traceback (most recent call last):
OSError: Not a gzipped file (b'+p')


Process finished with exit code 1

【问题讨论】:

    标签: python python-requests web-crawler search-engine bing


    【解决方案1】:

    开始使用 requests 库要容易得多。另外,这也是当今最常用的 http 请求库。

    在你的 python 环境中安装请求:

    pip install requests
    

    在您的 .py 文件中:

    import requests
    
    r = requests.get("http://www.bing.com")
    
    print(r.text)
    

    【讨论】:

    • 感谢回复,我试过你的代码,它只输出'',但它比很多二进制代码要好。那么有没有办法按照你所指的方式获取正常的首页内容呢?
    • 我猜你只是打印了请求对象,像这样:print(r)
    • @sylph001 是的,正如 Federico 指出的那样。你需要打印(r.text)或打印(r.content)
    【解决方案2】:
    OSError: Not a gzipped file (b'+p')
    

    您要么需要添加"accept-encoding: "gzip" or "br" 来请求headers,要么从响应中读取内容编码并选择正确的,或者使用requests 库代替,这将为您完成所有工作。

    可能出现的第二个问题,你需要传递一个user-agent来请求headers作为一个“真正的”用户访问。

    如果在使用requests 库时没有将user-agent 传递到请求headers,则默认为python-requests,因此必应或其他搜索引擎会理解它是机器人/脚本,并阻止请求。检查what's your user-agent

    使用requests 库传递user-agent

    headers = {
        'User-agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582'
    }
    
    requests.get('URL', headers=headers)
    

    How to reduce the chance of being blocked while web scraping search engines.


    或者,您可以使用来自 SerpApi 的 Bing Organic Results API 来实现相同的目的。这是一个带有免费计划的付费 API。

    不同之处在于,如果 HTML 布局不是最好的,您不必花时间尝试绕过 Bing 或其他搜索引擎的阻止或找出不同的繁琐问题,例如选择正确的 CSS 选择器.

    相反,请关注需要从结构化 JSON 中提取的数据。查看playground

    免责声明,我为 SerpApi 工作。

    【讨论】:

      猜你喜欢
      • 2013-01-20
      • 2019-11-30
      • 2011-02-19
      • 2014-08-05
      • 2012-01-04
      • 2012-07-02
      • 2020-04-14
      • 2011-10-03
      • 2015-06-01
      相关资源
      最近更新 更多