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

2024-06-07 14:09:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个代码,这将能够验证域通过whois.domaintools.com网站. 在

但是在读取html时有一个小问题,它与whoisdools.com/registereddos.com/.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

Tags: 代码comurlread网站responsehtmlerror
1条回答
网友
1楼 · 发布于 2024-06-07 14:09:00

如果您使用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()

相关问题 更多 >

    热门问题