首页 > 解决方案 > 遍历 url 列表时无法建立连接

问题描述

我想遍历 url 列表并使用请求打印状态代码

这是我的代码

import requests

file = open("urls.txt", "r+")

for urls in file:
    list = "https://" + urls
    r = requests.get(list)
    print(r.status_code)

这是我的 urls.txt

login.spotify.com
hrblog.spotify.com
lon.spotify.com
cms-change.spotify.com
upgrade.spotify.com
mydata.spotify.com
spclient.wg.spotify.com

这是我得到的错误

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='login.spotify.com%0a', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x03141A30>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

标签: pythonpython-requests

解决方案


当您从文件中读取行时,您必须\n从行尾删除,即。

urls = urls.strip()

顺便说一句: \n有十六进制代码0a,你可以在你的网址中看到它host='login.spotify.com%0a'


推荐阅读