python表单提交
来源:互联网 发布:python reverse() 编辑:程序博客网 时间:2024/06/05 15:37
python写爬虫模拟表单提交的库其实有很多,我使用的是Requests库进行简单的表单提交。
Requets 库安装方式:
sudo pip install requests一、无文件的表单提交
对于无文件的提交,我们只需要查看目标网页表单各元素的名字和我们要提交的值,然后写成一个结构体提交上去就可以了,比如下面的html代码。
<form action="http://xxx.xxx.com/xxx.php" enctype="multipart/form-data" method="post" id="uploadForm"><input type="hidden" value="doc" name="action" id="action_scan" /><p id="label_ocrLang">识别语言:<input value="2" id="ocr_china" name="ocrLang"/></p><p id="label_keyLang" >输出语言:<input value="0" id="key_eng_default" name="keyLang" /></p><button type="submit" id="start" class="button">submit</button> </form>从代码中可以看出,表单中需要提交的键值对有三对{action:doc},{ocrLang:2},{keyLang:0},表单会提交到http://xxx.xxx.com/xxx.php,所以对应的爬虫的python代码如下:
# -*- coding:utf-8 -*-import requests#要提交的键值对的一个结构keywords = { 'action':'doc', 'ocrLang':'2', 'keyLang':'0' }#表单要提交到的目的地址url = "http://xxx.xxx.com/xxx.php"#以post的方式提交表单并保存结果在变量r中r = requests.post(url,data = keywords)服务器返回的结果保存在变量r中,可以使用r.text得到返回的html代码,r.status得到返回的状态码等,具体的操作请查看requests的相关文档,另外本文只讲post方法,get方法类似,请找别的资料。
二、有文件的表单提交
对于有文件的表单提交也是类似的,用以下的html表单为例
<form action="http://xxx.xxx.com/xxx.php" enctype="multipart/form-data" method="post" id="uploadForm"><input type="hidden" value="doc" name="action" id="action_scan" /><p id="label_ocrLang">识别语言:<input value="2" id="ocr_china" name="ocrLang"/></p><p id="label_keyLang" >输出语言:<input value="0" id="key_eng_default" name="keyLang" /></p><p>要上传的图片1:<input type="file" name="img1" /><br>要上传的图片2:<input type="file" name="img2" /><p><button type="submit" id="start" class="button">submit</button> </form>
对于普通的input,用name和value的键值对的数据,而对于文件,同样要用该标签的name属性来做对应,需要使用多一个结构来提交:
# -*- coding:utf-8 -*-import requests#要提交的键值对的一个结构keywords = { 'action':'doc', 'ocrLang':'2', 'keyLang':'0' }#要提交的文件的一个结构,img1和img2为input标签的name属性,用来匹配文件作为哪个标签上传的文件,"file1.jpg"和"file2.jpg"为要上传的文件的路径,最好用完整路径,如"C:/file1.jpg"pictures = { 'img1':open("file1.jpg",'rb'), 'img2':open("file2.jpg",'rb') }#表单要提交到的目的地址url = "http://xxx.xxx.com/xxx.php"#以post的方式提交表单并保存结果在变量r中r = requests.post(url, data = keywords ,files = pictures)
0 0
- python进行表单提交
- python表单提交
- 用python模拟提交表单
- python get,post提交表单
- python get,post提交表单
- Python Flask-表单提交方式
- Python需要提交表单爬虫
- python提交表单和提交json
- python模拟登录及表单提交
- Python 模拟登录及表单提交
- python模拟登录及表单提交
- python模拟登录及表单提交
- Python提交表单并处理返回结果
- python get、post提交表单(headers)
- Python使用requests提交HTTP表单
- 表单提交
- 表单提交
- 表单提交
- 基本法求解位示图编号问题
- Git忽略规则及.gitignore规则不生效的解决办法
- RecyclerView使用详解(一)
- Java虚拟机学习(2):垃圾收集算法
- OPECNCV 3.0 机器学习算法总结
- python表单提交
- 动态广播和静态广播接收时间备注
- 判断一个范围内的哪些是质数
- caffe training instruction for image classification
- 16进制图片在jasperreport模板上显示
- UserDefault数据读取
- Action3D
- cocos2d-x中的init,onEnter,onExit......
- cocos2d安装配置及打包成Android