【问题标题】:In urllib3, HTTP request hangs ... but doesn't in curl在 urllib3 中,HTTP 请求挂起......但在 curl 中没有
【发布时间】:2019-04-26 00:23:01
【问题描述】:

(感谢您查看此内容!)

我正在尝试使用 python3 和简单的 urllib3 http.request 从https://login.morganstanleyclientserv.com 读取 HTML。

似乎服务器正在重置连接,最终 urllib3 的重试放弃了。

这里有 TLS 协商问题吗?如果是这样,urllib3如何补偿?

还是其他地方的问题?如何解决这个问题?


我已经使用 curl 尝试了相同的(?)事务......它会毫无延迟地返回预期的 HTML。

我也尝试过从其他网站阅读(例如,https://client.schwab.com/Login/SignOn/CustomerCenterLogin.aspx)...没问题。

Chrome 加载 https://login.morganstanleyclientserv.com 没有问题。

uname -a ; python3 -V 返回:

Linux ubuntu 4.18.0-17-generic #18~18.04.1-Ubuntu SMP Fri Mar 15 15:27:12 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux Python 3.6.7


这是有效的卷曲:

curl -v --user-agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36" --header "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3" --header "Accept-Encoding: text/plain" --header "Accept-Language: en-US,en;q=0.9" --output foo  https://login.morganstanleyclientserv.com 

这是挂起的 python3 + urllib3 代码(在打印 1 之后,然后是 2,但没有其他任何内容):

import urllib3
import certifi

print (1)
try:
    http = urllib3.PoolManager(cert_reqs = 'CERT_REQUIRED', 
                               ca_certs = certifi.where())

    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',
               'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
               'Accept-Encoding': 'text/plain',
               'Accept-Language':'en-US,en;q=0.9'
               }
    print (2)
# *** This hangs ***
    r = http.request("GET", "https://login.morganstanleyclientserv.com", headers)
    print (3)
    print (r.data)
    print (4)
except Exception as e:
    print(e)
except:
    print("error")

【问题讨论】:

  • 在 http.request 中尝试传递 headers=headers 而不仅仅是 headers

标签: python-3.x https urllib3


【解决方案1】:

作为一个 python 新手,我忽略了在 http.request 调用中命名 headers 参数。它应该是:

r = http.request("GET", "https://login.morganstanleyclientserv.com", headers=headers)

感谢 Edeki!

【讨论】:

    猜你喜欢
    • 2020-06-02
    • 1970-01-01
    • 2017-10-06
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多