首页 > 解决方案 > 我在终端上运行时得到 404,在空闲时得到 200

问题描述

代码:

import requests
file = open("test.txt")
for url in file:
    response = requests.get(url)
    print(response.status_code)

---------test.txt------------

https://www.google.com

终端中的 O/p:

404

当我在空闲时使用它时:

Python 3.6.8 (default, Oct  7 2019, 12:59:55)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> response = requests.get("https://google.com")
>>> response.status_code
200

标签: pythonpython-3.xpython-requests

解决方案


您文件中的每个url文件末尾都有一个换行符。试试看strip()

for url in file:
    response = requests.get(url.strip())

推荐阅读