2010-01-07 3 views
1
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 등) 은 내가 가진 오류가 있었다 반환합니다HTTP 코드를 가져 오려고합니다. 누군가이 파이썬 인터프리터에서이 코드를 사용해 볼 수 있고 왜 작동하지 않는지 볼 수 있습니까?

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

나는이 방법을 수행해야합니다. 즉, 대개 큰 비디오 파일을 전달합니다. "헤더"를 가져와 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 
>>> 
+1

오류 메시지가 아니라 추적을 게시해야합니다. –

+1

'http : // youtube.com /'에서 작동합니다 (301이 나옵니다). –

+2

파이썬 코드가 예상대로 작동합니다. 아마도 네버 서버의 실패일까요?/etc/hosts 파일을 살펴보십시오. – sberry

답변

2

코드는 나를 위해 일한 사람과 다른 사람 한테 효과가있었습니다. 이것은 사용중인 URL이 구문 분석에 문제가 있음을 의미합니다. headtail은 모두 호스트가 무엇인지 판단하기 위해 검사해야합니다. 예를 들면 : 당신이 headtail이 무엇인지 볼 수있게되면 정말 head을 해석 할 수 있어야합니다 경우

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

, 당신은 확인할 수 있습니다. 예를 들어, URL이 다음과 같은 경우 :

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

포트 번호로 인해 실패합니다.

+1

새롭게 편집 된 게시물을 확인할 수 있습니까? 정확히 'http://youtube.com'을 좋아했습니다. – TIMEX

+1

또는 find가 -1을 반환 할 것이므로 http://google.com과 같이 후행 슬래시를 생략하면됩니다. 머리는 google.co이고 꼬리는 m입니다. – sberry

+1

문제가 있습니다. 슬래시가 필요합니다. – sberry

2

Adam Crossland의 의견에 따르면 머리와 꼬리 값을 확인해야합니다. 귀하의 경우에는, 뒤에없이 당신이

head = "youtube.co" 
tail = "m" 

string.find 반환으로 끝날 -1 찾을 수없는 경우, 따라서 당신이 꼬리를 제외한 모든 머리 마지막 문자와 마지막 문자를 잡고있다 슬래시.

+2

Alex, urlparse 사용을 강력히 고려해야합니다. URL을 다루는 것이 더 효과적 일 것입니다 : http://docs.python.org/library/urlparse.html –

관련 문제