如何从特定网址获取正确的HTML代码(python)
我正在尝试写一段代码,能够通过 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 个回答
2
如果你用 print error
而不是 print error.read()
,你会看到服务器返回了一个 HTTP 403 "Forbidden" 的错误信息。
显然,这个服务器不喜欢没有用户代理头(user-agent header)的请求(或者它不喜欢 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()