python 利用requests模块会话session模拟登录URL网址下载数据
2017-07-22 17:57
417 查看
PASSWORD = '[{"userId":"**","password":"**"}]'
def getData():
s = requests.Session()#创建一个session对象
s.keep_alive = False #保持一个长连接
s.headers.update({'Connection': 'keep-alive'})
for i in range(0,5):
try:
s.post('URL',data=PASSWORD)#该URL为登录页面的URL
s.headers.update({'Content-Type': 'application/x-www-form-urlencoded'})
break
except requests.exceptions.ConnectionError:
time.sleep(1)
continue
s.headers.update({'Content-Type': 'application/x-www-form-urlencoded'})
payload = ''
for count in range(0,5):
print count
try:
rsp = s.post('URL',data=payload)#该URL为需要获取数据页面的F12请求正文内容
#print "rsp",rsp
break
except requests.exceptions.ConnectionError:
time.sleep(1)
continue
#print "rsp",rsp
exportfile ="D:/data.xls"
with open(exportfile,'wb') as out_file:
for chunk in rsp.iter_content():#将文本流保存到文件
out_file.write(chunk)
#若数据无效,则删除文件
f = open(exportfile, 'rb')
lines = f.read()
isinvalid=re.search("javascript",lines)
if (len(lines)==0) or (isinvalid is not None):
print "this is empty data,system will delete it"
f.close()
os.remove(exportfile)
else:
print "this is valid data"
time.sleep(40)
def getData():
s = requests.Session()#创建一个session对象
s.keep_alive = False #保持一个长连接
s.headers.update({'Connection': 'keep-alive'})
for i in range(0,5):
try:
s.post('URL',data=PASSWORD)#该URL为登录页面的URL
s.headers.update({'Content-Type': 'application/x-www-form-urlencoded'})
break
except requests.exceptions.ConnectionError:
time.sleep(1)
continue
s.headers.update({'Content-Type': 'application/x-www-form-urlencoded'})
payload = ''
for count in range(0,5):
print count
try:
rsp = s.post('URL',data=payload)#该URL为需要获取数据页面的F12请求正文内容
#print "rsp",rsp
break
except requests.exceptions.ConnectionError:
time.sleep(1)
continue
#print "rsp",rsp
exportfile ="D:/data.xls"
with open(exportfile,'wb') as out_file:
for chunk in rsp.iter_content():#将文本流保存到文件
out_file.write(chunk)
#若数据无效,则删除文件
f = open(exportfile, 'rb')
lines = f.read()
isinvalid=re.search("javascript",lines)
if (len(lines)==0) or (isinvalid is not None):
print "this is empty data,system will delete it"
f.close()
os.remove(exportfile)
else:
print "this is valid data"
time.sleep(40)
相关文章推荐
- Python中Django框架利用url来控制登录的方法
- python第三次采集数据小记之登录下载
- [python和大数据-1]利用爬虫登录知乎进行BFS搜索抓取用户信息本地mysql分析【PART1】
- URL下载数据、模拟登录或上传
- 利用python读取csv中url并下载
- Python中Django框架利用url来控制登录的方法
- 利用Python调用ECMWF欧洲中心API批量下载数据
- 利用python进行数据分析(四):数据加载、存储
- 使用Python批量下载数据
- HttpURLConnection:网络下载数据的工具类
- [Python]网络爬虫(二):利用urllib2通过指定的URL抓取网页内容
- 利用python进行数据分析(六):绘图和可视化
- Python 利用字典计算数据中不重复的数量
- 利用 Python 进行数据分析(九)pandas 汇总统计和计算
- 利用Python进行数据分析(15) pandas基础: 字符串操作
- 利用python进行数据分析-数据规整化1
- 利用 Python 进行数据分析(十二)pandas:数据合并
- 利用Python编写网络爬虫下载文章
- handler、HttpURLConnection、网络数据下载综合使用。
- 利用Python进行数据分析 学习笔记