python - 如何在循环中运行函数,从文件中逐行提取参数
问题描述
我正在编写一个脚本,该脚本将 url、用户名和密码作为参数,发出 Web 请求并记录结果。我想使用一个包含许多站点/凭据的 csv 文件,并循环每个条目的请求,如果有任何异常/错误,我只想跳到文件中的下一个条目,但我的脚本在第一次运行后挂起循环
目前我只是通过命令行标志手动传递参数,但这不可行,因为手动执行需要很长时间当我尝试创建循环并从文件中提取参数时,我的函数运行一次然后挂起无限期地,无论是否存在例外,都会发生这种情况。
#currently Im using command line arguments to manually input the
#arguments for the function below, which works fine but I want to pull
#arguments from a list in a csv file (see comments at end for what ive #tried)
def webrequest(username,password):
url = site
headers = {'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
'Accept-Encoding' : 'none'
}
payload = {'log': username,
'pwd': password
}
session = requests.session
r = session.post(url, headers=headers, data=payload)
if r.status_code == 404
print "404"
#end function, move on to next line in csv
if r.status_code == 200
print r.text
# move on to next line in csv
#file = open(file, r)
#with open(file) as f:
# for line in f:
# args = line.split(",")
# webrequest(args[0],args[1],args[2])
我希望当函数到达末尾时使用 csv 文件中的下一行重新开始,但它没有......它只是挂在命令行
解决方案
使用 timeout 参数尝试 session.post()。详细信息:http: //docs.python-requests.org/en/master/user/advanced/#timeouts
很可能您的 Web 服务器没有返回响应,所以您觉得您的功能被卡住了。
推荐阅读
- ios - 将照片库中的图像导入xcode中的应用程序
- jquery - 从 MVC 中剃刀视图上的 Ajax 成功功能跳转/重新加载到同一页面
- windows - RegisterPointerInputTarget 不消耗所有输入
- c# - 带有文本框的 WPF Excel 类似箭头键功能
- json - 如何从杰克逊 ObjectMapper 中获取 JSON
- java - 如何使用 Selenium 将文件上传到 Div 标签。哪个标签没有输入作为类型
- live-streaming - 使用 HLS 处理实时流式传输中的变体
- python - AmbiguousForeignKeysError 即使在指定 foreign_keys 之后
- c# - 如何创建一个集中的表达式提供者
> 有不同的类型? - django - 姜戈。将字段类型 UUIDField 更改为 CharField