【问题标题】:HTTPS request in python 2.7python 2.7中的HTTPS请求
【发布时间】:2014-04-01 22:50:00
【问题描述】:

我找不到这方面的文档。是否可以在 python 2.7 中运行 https 请求?

我在 3.2 中尝试了此代码,但这些模块在 2.7 中不存在。

import urllib.request
r = urllib.request.urlopen('https://openapi.etsy.com/v2/users/redluck2013/profile?        fields=transaction_sold_count&api_key=1pmmjgt3j4nz5ollhzz2hvib')
print(r.read())

【问题讨论】:

    标签: python linux https command


    【解决方案1】:

    关于https,请注意:

    Warning HTTPS requests do not do any verification of the server’s certificate.
    

    http://docs.python.org/2/library/urllib2.html

    如果你确实需要 https 验证,python requests 是一个非常有用的库

    import requests
    url = https://openapi.etsy.com/v2/users/redluck2013/profile?fields=transaction_sold_count&api_key=1pmmjgt3j4nz5ollhzz2hvib
    r = requests.get(url, verify=True)
    content = r.text
    

    对于验证,只需确保将 True 传递给 verify 参数。

    更多:

    【讨论】:

    • 代码不是有效的 Python。此外,您不需要显式的 verify=True,例如,requests.get('https://docs.python-requests.org') 失败,因为主机名不匹配。
    【解决方案2】:

    使用 2.7:

    import urllib2
    
    r = urllib2.urlopen('https://openapi.etsy.com/v2/users/redluck2013/profile?fields=transaction_sold_count&api_key=1pmmjgt3j4nz5ollhzz2hvib')
    
    print(r.read())
    

    http://docs.python.org/2/howto/urllib2.html

    【讨论】:

      【解决方案3】:

      urllib.request是在python 3中添加的,它在python 2.7中不存在。

      在 python 2.7 中,使用urllib.urlopen

      这与https无关。

      【讨论】:

        猜你喜欢
        • 2012-04-08
        • 2016-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-28
        • 1970-01-01
        相关资源
        最近更新 更多