【问题标题】:Get html and headers from single request using Python使用 Python 从单个请求中获取 html 和标头
【发布时间】:2012-06-08 12:29:15
【问题描述】:

我正在研究使用 python 发出单个 http 请求以检索 html 和 http 标头信息的可能性,而不必进行 2 个单独的调用。

有人知道什么好方法吗?

此外,发出这些请求的不同方法之间的性能差异是什么,例如urllib2 和 httpconnection 等

【问题讨论】:

    标签: python urllib2 httpconnection


    【解决方案1】:

    只需使用urllib2.urlopen()。可以通过调用返回对象的read() 方法来检索HTML,并且标题在headers 属性中可用。

    import urllib2
    f = urllib2.urlopen('http://www.google.com')
    
    >>> print f.headers
    Date: Fri, 08 Jun 2012 12:57:25 GMT
    Expires: -1
    Cache-Control: private, max-age=0
    Content-Type: text/html; charset=ISO-8859-1
    Server: gws
    X-XSS-Protection: 1; mode=block
    X-Frame-Options: SAMEORIGIN
    Connection: close
    
    >>> print f.read()
    <!doctype html><html itemscope itemtype="http://schema.org/WebPage"><head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
    ... etc ...
    

    【讨论】:

      【解决方案2】:

      如果您使用HTTPResponse,您可以使用两个函数调用来获取标题和内容,但它不会两次访问服务器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-21
        • 1970-01-01
        • 1970-01-01
        • 2022-08-07
        • 2015-03-04
        • 1970-01-01
        相关资源
        最近更新 更多