【问题标题】:urllib.request.urlopen is behaving strange. Not returning the data the next day. Why?urllib.request.urlopen 的行为很奇怪。第二天不返回数据。为什么?
【发布时间】:2018-02-04 23:50:26
【问题描述】:

我正在尝试使用 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")

这两种情况的结果相同。

请帮助。

【问题讨论】:

  • 我得到了和你一样的回应。
  • 这很奇怪……有时我明白,有时却没有
  • 好吧,我也没有在浏览器中得到合理的响应。

标签: python json urllib


【解决方案1】:

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

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

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

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

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

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

【讨论】:

  • 是的,我绝对同意您的回复。我也测试过这个。当我更改为不同的 IP 地址时,一切都开始运作良好。
  • 有3种错误 1.响应中没有min_position 2.时间线搜索响应中没有json 2.响应为空,最好分别测试和分析原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多