Python Requests如何传递IP地址而非URL链接

3
我想在Python中的请求中传递IP地址而不是URL链接。
例如:传递IP地址而不是URL链接:
requests.get(url="172.217.168.228")
所以基本上是传递IP地址而不是URL链接。我该如何实现呢?
我猜我应该传递相关端口,但是怎么做呢?
我试了几件事情,但我得到了一堆错误,比如:
requests.exceptions.MissingSchema: Invalid URL '172.217.168.228': No schema supplied. Perhaps you meant http://172.217.168.228?

或者

 File "/Users/ali/Desktop/cdn-detection/venv/lib/python3.9/site-packages/requests/adapters.py", line 514, in send
    raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='172.217.168.228', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1129)')))

或者

File "/Users/ali/Desktop/cdn-detection/venv/lib/python3.9/site-packages/requests/adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='172.217.168.228.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f9be196a0a0>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'))

你可以使用IP地址代替主机名,但仍需要一个方案(http或https),这就是为什么会出现“MissingSchema”异常的原因。使用"https://172.217.168.228" - DisappointedByUnaccountableMod
1个回答

4

您需要告诉requests模块伪造Host头信息,并将URL中的主机名替换为IP地址:

requests.get("http://172.217.168.228", headers={"Host": "www.google.com"})

for more info, you can see this link


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接