python - 尝试获取 HTTP 代码。有人可以在他们的 Python 解释器中为我尝试这段代码,看看为什么它不起作用吗?

标签 python http exception url

import httplib
def httpCode(theurl):
    if theurl.startswith("http://"): theurl = theurl[7:]
    head = theurl[:theurl.find('/')]
    tail = theurl[theurl.find('/'):]
    response_code = 0
    conn = httplib.HTTPConnection(head)
    conn.request("HEAD",tail)
    res = conn.getresponse()
    response_code = int(res.status)
    return response_code

基本上,此函数将接受一个 URL 并返回其 HTTP 代码(200、404 等) 我得到的错误是:

Exception Value:  (-2, 'Name or service not known')

我必须用这个方法来做。也就是说,我通常传递大型视频文件。我需要获取“ header ”并获取 HTTP 代码。我不能下载文件然后获取 HTTP 代码,因为这会花费太长时间。

Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import httplib
>>> def httpCode(theurl):
...     if theurl.startswith("http://"): theurl = theurl[7:]
...     head = theurl[:theurl.find('/')]
...     tail = theurl[theurl.find('/'):]
...     response_code = 0
...     conn = httplib.HTTPConnection(head)
...     conn.request("HEAD",tail)
...     res = conn.getresponse()
...     response_code = int(res.status)
...     print response_code
...
>>> httpCode('http://youtube.com')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in httpCode
  File "/usr/lib/python2.6/httplib.py", line 874, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python2.6/httplib.py", line 911, in _send_request
    self.endheaders()
  File "/usr/lib/python2.6/httplib.py", line 868, in endheaders
    self._send_output()
  File "/usr/lib/python2.6/httplib.py", line 740, in _send_output
    self.send(msg)
  File "/usr/lib/python2.6/httplib.py", line 699, in send
    self.connect()
  File "/usr/lib/python2.6/httplib.py", line 683, in connect
    self.timeout)
  File "/usr/lib/python2.6/socket.py", line 498, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
>>>

最佳答案

您的代码对我有用,对另一个发表评论的人也有用。这意味着您正在使用的 URL 以某种方式导致您的解析出现问题。 headtail 都应该被检查以确定它认为主机是什么。例如:

head = theurl[:theurl.find('/')]
print head
tail = theurl[theurl.find('/'):]
print tail

一旦您看到headtail 是什么,您就可以确定它是否真的应该能够解析head。例如,如果 url 是:

http://myhost.com:8080/blah/blah

它会因为端口号而失败。

关于python - 尝试获取 HTTP 代码。有人可以在他们的 Python 解释器中为我尝试这段代码,看看为什么它不起作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2023312/

相关文章:

python - 如何在Python中明智地访问列表列表中的元素

python - 每n秒在for循环中打印一些东西

haskell - 为什么这个 try catch 示例不起作用

java - 修改java代码错误

python 访问返回的变量

python:在另一个文件夹中运行测试的文件夹覆盖(Eclipse PyDev)

http - http.Server 的奇怪行为 - 为每个客户端建立三个连接?

python - 如何使用 epoll 和 python 3.1 进行异步 http 请求

javascript - AngularJS:避免在收到响应之前两次调用相同的 REST 服务

C++ 异常:为什么要使用或扩展 std::exception?