【问题标题】:How to get right HTML code from a concrete URL (python)如何从具体的 URL (python) 获取正确的 HTML 代码
【发布时间】:2011-06-08 11:10:40
【问题描述】:

我正在尝试编写一个代码,它将能够通过 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

【问题讨论】:

    标签: python html url urllib


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      相关资源
      最近更新 更多