gpt4 book ai didi

python - urllib.request.urlopen 的行为很奇怪。第二天不返回数据。为什么?

转载 作者:太空宇宙 更新时间:2023-11-03 14:50:49 25 4
gpt4 key购买 nike

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

****方法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 似乎会根据您的 IP 地址和用户代理 (UA) 字符串,通过重复点击搜索 URL 来检测自动抓取。在某些时候,后续的点击会返回空结果。这似乎是在一天左右之后发生的,可能是 Twitter 方面分析延迟的结果。

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

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

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

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

关于python - urllib.request.urlopen 的行为很奇怪。第二天不返回数据。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45906631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com