urllib.request.urlopen是表现奇怪。第二天不返回数据。为什么?
我想读通过URL Twitter的饲料。昨天我能拉使用的代码和一些80K鸣叫,由于我的机器上的一些更新,我的Mac终端停止完成Python代码之前响应。urllib.request.urlopen是表现奇怪。第二天不返回数据。为什么?
今天,同样的代码不会返回任何JSON数据。这是扔给我空的结果。虽然如果我在浏览器中输入相同的URL,我可以得到一个充满数据的json文件。
这是我的代码: 方法1:
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}
****方法2:****
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的自动检测通过对搜索URL重复命中刮,根据您的IP地址和用户代理(UA)字符串。在某些时候,随后的命中返回空结果。这似乎发生在一天左右之后,可能是由于推特分析的延迟。
如果更改搜索URL请求头中的UA字符串,应再次接收应答中的有效结果。 Twitter可能会在一段时间后再次阻止你,所以你需要经常更换你的UA字符串。
我认为Twitter的一些到期后超时这些块,但我不知道过了多久,将采取。
作为参考,该twitter-past-crawler project演示了使用从包含多个UA串的文件中取出的半随机UA字符串。
此外,Twitter-Search-API-Python项目使用硬编码的UA字符串,它停止了我的第一次测试后一天左右的工作。更改代码中的字符串(添加随机字符)会导致恢复之前的功能。
是的,绝对我同意你的回应。我也测试过了。当我改变到不同的IP地址时,事情开始运作良好。 –
我得到同样的响应,你怎么做。 – elena
奇怪的是正确的。有时我得到它,有时不 –
嘛,我不要在浏览器中得到合理的回应要么。 – elena