Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从txt文件中使用请求和读取URL_Python_Python 3.x - Fatal编程技术网

Python 如何从txt文件中使用请求和读取URL

Python 如何从txt文件中使用请求和读取URL,python,python-3.x,Python,Python 3.x,我正在写一段代码,其中我在一个文件中有一个URL列表,我使用请求遍历该文件,执行GET请求并打印状态代码,但从我所写的代码中,我没有得到任何输出 import requests with open('demofile.txt','r') as http: for req in http: page=requests.get(req) print page.status_code 我发现了两个问题,一个是您忘记在for循环之后缩进行,另一个是您未能删除最后一行\n(假

我正在写一段代码,其中我在一个文件中有一个URL列表,我使用请求遍历该文件,执行GET请求并打印状态代码,但从我所写的代码中,我没有得到任何输出

import requests
with open('demofile.txt','r') as http:
    for req in http:
     page=requests.get(req)
     print page.status_code

我发现了两个问题,一个是您忘记在
for
循环之后缩进行,另一个是您未能删除最后一行
\n
(假设URL在不同的行中分开)


我发现了两个问题,一个是您忘记在
for
循环之后缩进行,另一个是您未能删除最后一行
\n
(假设URL在不同的行中分开)


for循环是否应该不在with语句中?看起来你错过了一个级别的indentation@scotty3785oops my bad it’s本意正确,在提交
打印页面上出错。状态\u code
为您的标记提供了错误。for循环是否应该不在with语句中?看起来你错过了一个级别的indentation@scotty3785oops my bad it’s本意正确,在提交<代码>打印页面上出错。状态\u代码为您的标记提供了一个错误。只需进行一小次编辑即可添加页面=请求。获取(“http://”+req)为了避免模式错误,现在必须找到一种绕过SSL验证的方法。在http:中为req使用
的语法是有效的,但正如您所说的,现在需要去掉新行。另一种方法是:
data=open('deleteme','r')。读取()
,然后对数据中的行执行
。拆分行()
,这也将为您消除行结尾。不幸的是,这需要整个文件的内容驻留在内存中。(注意:在Python3.x中,使用
data=open('deleteme','r').read().decode('utf-8')
只需进行一小部分编辑即可添加page=requests.get(“http://“+req”)为了避免模式错误,现在必须找到一种绕过SSL验证的方法。在http:
中为req使用
的语法是有效的,但正如您所说的,现在有新行要删除。另一种方法是:
data=open('deleteme','r')。read()
,然后
为数据中的行。splitlines()
这也将为您消除行尾。不幸的是,这需要整个文件的内容驻留在内存中。(注意:在python 3.x中,使用
data=open('deleteme','r')。read().decode('utf-8')
import requests

with open('deleteme','r') as urls:
    for url in urls.readlines():
        req = url.strip()
        print(req)
        page=requests.get(req)
        print(page.status_code)