如何从具体的URL(python)中获取正确的HTML代码

时间:2011-06-08 11:10:40

标签: python html url urllib

我正在尝试编写代码,可以通过whois.domaintools.com验证域名。

但是阅读html有点问题,那与whois.domaintools.com/notregistereddomain.com源代码不符。怎么了?它的问题还是什么?我真的不知道如何解决它。

import urllib2

def getPage():
    url="http://whois.domaintools.com/notregistereddomain.com"

    req = urllib2.Request(url)

    try:
        response = urllib2.urlopen(req)
        return response.read()
    except urllib2.HTTPError, error:
        print "error: ", error.read()
        a = error.read()
        f = open("URL.txt", "a")
        f.write(a)
        f.close()


if __name__ == "__main__":
    namesPage = getPage()
    print namesPage

1 个答案:

答案 0 :(得分:2)

如果您使用print error代替print error.read(),则会看到您从服务器获得HTTP 403“禁止”答案。

显然这个服务器不喜欢没有用户代理头的请求(或者它不喜欢Python的那个,因为它不想从脚本中查询)。这是一个解决方法:

user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)" # Or any valid user agent from a real browser
headers = {"User-Agent": user_agent}
req = urllib2.Request(url, headers=headers)
res = urllib2.urlopen(req)
print res.read()