【问题标题】:Urllib2.urlopen and request freezesUrllib2.urlopen 和请求冻结
【发布时间】:2024-01-10 01:32:01
【问题描述】:

编辑:我发现我犯了一个错误,因为错误的原因不是 urllib 而是 nltk,它无法处理来自这个确切页面的长字符串。对不起这个。

我不知道为什么,但是无论我使用 Urllib2.urlopen 还是遇到特定 url 时的请求。

import requests
r = requests.get('SomeURL')
print html = r.text

这是它的行为。 1)当我想到一个包含 200 个 url 的循环时,它每次都会在完全相同的 URL 处冻结。如果我不终止程序,它会在这里停留几个小时。 2)当您尝试仅使用循环外的代码示例时,它可以工作。 3)如果我只是将这个 url 列入黑名单,它会毫无问题地通过循环。

它实际上不返回任何类型的错误代码,它在循环之外运行良好,并且设置了超时,但它没有做任何事情。它仍然会无限期挂起。

那么有没有其他方法可以在一定时间后强制停止http get请求,因为超时不起作用。除了 urllib2 和 request 之外还有其他库可以完成这项工作,并且遵循超时限制吗?

for i in range(0,mincount):
    code(call the request for urlist[i]) 
    It always works but freezes only when I request this site. If i had 200 request to yahoo   for example it would work. But when i try go to this particular url i cannot.  
#end

edit:这是一个循环的标准,没有太大的错误空间。

【问题讨论】:

  • 我正在尝试这个模块。
  • timeout 选项有效。这可能是由于您的循环代码。您可以添加代码的循环部分吗?您在该部分使用while 声明吗?
  • httplib2 在 for 循环中仍然不起作用。我什至无法猜测循环中的什么会导致仅针对一个 URL 的 3 种独立类型的 http 请求(urllib2、request 和 httplib2 不起作用)。

标签: python python-2.7 web get httprequest


【解决方案1】:

我认为这只是一个非常慢的页面;在我的系统上,加载大约需要 9.7 秒。

如果你试图在一个短循环中运行它,它确实似乎会冻结。

你可以试试

links = [
    'SomeURL',
    'http://www.google.com/'
]

for link in links:
    try:
        html = requests.get(link, timeout=2.).content
        print("Successfully loaded {}".format(link))
    except requests.Timeout:
        print("Timed out loading {}".format(link))

这给了我

Timed out loading SomeURL
Successfully loaded http://www.google.com/

【讨论】:

  • 我尝试了几次循环,但每次在 1000 多秒后都没有加载。 python ajax 网站有问题吗?
  • 实际上,我使用的 for 循环似乎只有某种错误。这个东西对我来说也在 10 秒内加载,但它在循环时不会加载。有趣的是,yahoo.com 和任何其他网站都在循环中工作,但这个网站没有。