博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python自动化测试 (九)urllib2 发送HTTP Request
阅读量:4677 次
发布时间:2019-06-09

本文共 1755 字,大约阅读时间需要 5 分钟。

urllib2 是Python自带的标准模块, 用来发送HTTP Request的。  类似于 .NET中的,  HttpWebRequest类

 

urllib2 的优点

Python urllib2 发出的HTTP Request, 能自动被Fiddler截获, 方便了调试。

Python 可以自动处理Cookie

 

urllib2 的缺点

Python urllib2 发出的http Request, 中的header 会被修改成“首字母大写”,

比如你的代码里写的header 是: content-TYPE=application/x-www-form-urlencoded ,  会被修改为 Content-Type=application/x-www-form-urlencoded

 

实例一,  Get方法, 并且自定义header

 

# -* - coding: UTF-8 -* -  import urllib2request = urllib2.Request("http://www.baidu.com/")request.add_header('content-TYPE', 'application/x-www-form-urlencoded')response = urllib2.urlopen(request)print response.getcode()print response.geturl()print response.read()

 

实例二, post方法

 

# -* - coding: UTF-8 -* -  import urllib2import urllibrequest = urllib2.Request("http://passport.cnblogs.com/login.aspx")request.add_header('content-TYPE', 'application/x-www-form-urlencoded')data={
"tbUserName":"test_username", "tbPassword":"test_password"}response = urllib2.urlopen(request, urllib.urlencode(data))print response.getcode()print response.geturl()print response.read()

 

实例三: Cookie 的处理

 

# -* - coding: UTF-8 -* -  import urllib2import urllibimport cookielibcj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))request = urllib2.Request("https://dynamic.12306.cn/otsweb/")request.add_header('content-TYPE', 'application/x-www-form-urlencoded')data={
"tbUserName":"test_username", "tbPassword":"test_password"}response = opener.open(request, urllib.urlencode(data))# send again, you will see cookie sent to web serverresponse = opener.open(request, urllib.urlencode(data))print response.getcode()print response.geturl()print response.read()

 

实例四:如何处理跳转

创建Opener时, ul2.HTTPRedirectHandler是默认被加上的handler之一 

 

 

 

转载于:https://www.cnblogs.com/TankXiao/p/3081312.html

你可能感兴趣的文章
两种分页方案
查看>>
centos7上建立vnc server
查看>>
《麻辣江湖》即将上线!
查看>>
Mybatis中mapper.xml文件判断语句中的单双引号问题
查看>>
frameset和frame
查看>>
饥饿的小易(规律,同余大数)
查看>>
ats透明代理
查看>>
PHP 小代码
查看>>
2016/03/16 codes
查看>>
2018年7月21日工作总结
查看>>
Linux shell 命令判断执行语法 ; , && , ||
查看>>
vim代码格式化插件clang-format
查看>>
Android字体加粗
查看>>
asp.net运行机制与页面生命周期
查看>>
【Qt常见问题】系列01
查看>>
windows和ubuntu虚拟机设置共享文件夹,在windows中用source insight阅读和编写代码,在linux中用交叉编译工具编译。...
查看>>
js入坑第一天
查看>>
ubuntu16.04 Detectron目标检测库配置(包含GPU驱动,Cuda,Caffee2等配置梳理)
查看>>
D - Going Home POJ - 2195 网络流
查看>>
Java基础知识强化93:算一下你来到这个世界多少天的案例
查看>>