![](/img/trans.png)
[英]How do I convert a human-readable date + time to a Unix timestamp in Python?
[英]How do I convert Python crawled Bing web page content to human-readable?
我正在玩使用 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
开始使用请求库要容易得多。 另外,这也是当今HTTP请求最常用的库。
在您的python环境中安装请求:
pip install requests
在您的.py文件中:
import requests
r = requests.get("http://www.bing.com")
print(r.text)
除了Zilong Li 的回答,您还需要通过一个user-agent
来请求headers
以充当“真正的”用户访问。
如果在使用requests
库时没有user-agent
被传递到请求headers
,它默认为python-requests,所以 Bing 或其他搜索引擎会理解它是一个机器人/脚本,并阻止请求。 检查您的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)
或者,您可以使用 SerpApi 的Bing Organic Results API实现相同的目的。 这是一个带有免费计划的付费 API。
不同之处在于您不必花时间试图绕过 Bing 或其他搜索引擎的阻止。 相反,应关注需要从结构化 JSON 中提取的数据。 看看操场。
免责声明,我为 SerpApi 工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.