urllib.request.urlopen 表现异常。第二天不返回数据。为什么?

urllib.request.urlopen is behaving strange. Not returning the data the next day. Why?

我正在尝试使用 URL 阅读 Twitter 提要。昨天我能够使用代码提取一些 80K 推文,并且由于我的机器上的一些更新,我的 Mac 终端在 python 代码完成之前停止响应。

今天相同的代码没有返回任何 json 数据。它让我空洞的结果。而如果我在浏览器中键入相同的 URL,我可以获得一个包含完整数据的 json 文件。

这是我的代码: 方法一:

try:
    urllib.request.urlcleanup()
    response = urllib.request.urlopen(url)
    print('URL to  used: ', url)
    testURL = response.geturl()
    print('URL you used: ', testURL)
    jsonResponse = response.read()
    jsonResponse = urllib.request.urlopen(url).read()

这打印了:

URL to  used:  https://twitter.com/i/search/timeline?f=tweets&q=%20since%3A2017-08-14%20until%3A2017-08-15%20USA&src=typd&max_position=
URL you used:  https://twitter.com/i/search/timeline?f=tweets&q=%20since%3A2017-08-14%20until%3A2017-08-15%20USA&src=typd&max_position=
json:  {'items_html': '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n', 'focused_refresh_interval': 30000, 'has_more_items': False, 'min_position': 'TWEET--', 'new_latent_count': 0}

****方法二:****

try:
    request = urllib.request.Request(url, headers=headers)
except:
    print("Thats the problem here:")

try:
    response = urllib.request.urlopen(request)
except:
    print("Exception while fetching response")

testURL = response.geturl()
print('URL you used: ', testURL)

try:
    jsonResponse = response.read()
except:
    print("Exception while reading response")

两种情况下的结果相同。

请帮忙。

根据我的测试,此行为与 urllib 无关。例如,requests 库也会发生同样的事情。

Twitter 似乎会根据您的 IP 地址和用户代理 (UA) 字符串通过重复点击搜索 URL 来检测自动抓取。在某些时候,后续命中 return 空结果。这似乎是在一天左右后发生的,可能是 Twitter 部分延迟分析的结果。

如果您在搜索 URL 请求 header 中更改 UA 字符串,您应该会再次在响应中收到有效结果。 Twitter 可能会在一段时间后再次阻止您,因此您需要经常更改 UA 字符串。

我假设 Twitter 在超时后会过期这些块,但我不知道这需要多长时间。

作为参考,twitter-past-crawler project 演示了如何使用从包含多个 UA 字符串的文件中获取的 semi-random UA 字符串。

此外,Twitter-Search-API-Python 项目使用硬编码的 UA 字符串,在我第一次测试后一天左右就停止工作了。更改代码中的字符串(添加随机字符)导致恢复先前的功能。