如何验证url是否存在不重定向?

时间:2015-03-08 12:26:41

标签: python

如何验证页面网址是否存在而不是重定向到未找到的网址页面 例如:

import socket
try:
    socket.gethostbyname('www.google.com/imghp')
except socket.gaierror as ex:
    print "Not existe"

它撤退不存在

2 个答案:

答案 0 :(得分:3)

您正在使用错误的工具完成任务!

screw hammer

来自manual

  

<强> socket.gethostbyname(主机名)

     

将主机名转换为IPv4地址格式。 IPv4地址以字符串形式返回,例如&#39; 100.50.200.5&#39;。如果主机名是IPv4地址本身,则返回不变。有关更完整的界面,请参阅gethostbyname_ex()。 gethostbyname()不支持IPv6名称解析,而应使用getaddrinfo()代替IPv4 / v6双栈支持。

该工具用于检查是否存在,并获取其IP地址:

>>> try:
...     print(socket.gethostbyname('www.google.com'))
... except socket.gaierror as ex:
...     print("Does not exists")
... 
216.58.211.132

您可能想要的是实际连接到网站并检查是否有页面:

>>> import requests
>>> response = requests.head('http://www.google.com/imghp')
>>> if response.status_code == 404:
...    print("Does not exists")
... else:
...    print("Exists")
...
Exists

来自.head()方法仅从网络服务器获取有关该网页的信息,而不是网页本身,因此它在网络使用方面非常轻量级。

扰流警报:如果您尝试使用response.content获取网页内容,则无法获得任何内容,因为您需要使用{{3}方法。


更新#1

您正在检查的网站已损坏,即它不符合互联网标准。它没有给出404,而是让302重定向到&#34;页面不存在&#34;状态代码为200的页面:

>>> response = requests.head('http://qamarsoft.com/does_not_exists', allow_redirects=True)
>>> response.status_code
200

要对其进行排序,您需要获取该网站的页面,并检查重定向网址中重定向的URI是否为404

>>> response = requests.head('http://qamarsoft.com/does_not_exists'
>>> response.headers['location']
'http://qamarsoft.com/404'

所以测试将成为:

>>> response = requests.head('http://qamarsoft.com/does_not_exists')
>>> if '404' in response.headers['location']:
...     print('Does not exists')
... else:
...     print('Exists')
Exists

更新#2

对于第二个URL,您可以在python控制台中自行尝试:

>>> import requests
>>> response = requests.head('http://www.***********.ma/does_not_Exists')
>>> if response.status_code == 404:
...    print("Does not exists")
... else:
...    print("Exists")
...
Does not exists
>>> response = requests.head('http://www.***********.ma/annonceur/a/3550/n.php ')
>>> if response.status_code == 404:
...    print("Does not exists")
... else:
...    print("Exists")
...
Exists

Nota Bene

您可能需要安装requests包:

pip install requests

或者如果您现代化并使用python3:

pip3 install requests

答案 1 :(得分:0)

对于gethostbyname(),你不会得到你想做的事情。考虑使用urllib2。在您的情况下,以下可以做您想要的:

import urllib2

#The data variable can be used to send POST data
data=None
#Here add as many header fields as you wish
headers={"User-agent":"Blahblah", "Cookie":"yourcookievalues"}
url = "http://www.google.com/imghp"
request = urllib2.Request(url, data, headers)
try:
    response = urllib2.urlopen(request)
    #Check redirection here
    if (response.geturl() != url):
         print "The page at: "+url+" redirected to: "+response.geturl()
except urllib2.HTTPError as err:
    #Catch 404s etc.
    print "Failed with code: "+str(err)

希望这会帮助你!