python爬虫-urllib+cookie+json+POST
2017-04-19 21:23
609 查看
原文链接: python爬虫-urllib+cookie+json+POST
发送json, 去掉
urlopen是一个封装好的OpenerDirector实例,参数为(url, data, timeout)
通过build_opener可以创建OpenerDirector实例, build_opener(*handlers), 将handler类实例化增加到OpenerDirector中
使用urllib2.install_opener()会设置urllib2的全局opener, 也可以直接调用opener.open()代替全局的urlopen方法
如果已知cookie内容, 且固定不变, 可以在header中直接添加cookie内容发送请求
python3与python2.7部分区别:
python 3.x中urllib库和urilib2库合并为urllib库
urllib2.urlopen变为urllib.request.urlopen
urllib2.Request变为urllib.request.Request
urllib2.urlencode()变为urllib.parse.urlencode
cookielib变为http.cookiejar
import urllib.request from http.cookiejar import CookieJar import json url = 'http://www.baidu.com' req_dict = {'k': 'v'} cj = CookieJar() handler = urllib.request.HTTPCookieProcessor(cj) opener = urllib.request.build_opener(handler) req_json = json.dumps(req_dict) req_post = req_json.encode('utf-8') headers = {} #headers['Content-Type'] = 'application/json' req = urllib.request.Request(url=url, data=req_post, headers=headers) #urllib.request.install_opener(opener) #res = urllib.request.urlopen(req) # 或 res = opener.open(req) res = res.read().decode('utf-8') print(res)
发送json, 去掉
headers['Content-Type'] = 'application/json'注释即可
相关知识:
默认的urllib.request.urlopen()不带cookie信息urlopen是一个封装好的OpenerDirector实例,参数为(url, data, timeout)
通过build_opener可以创建OpenerDirector实例, build_opener(*handlers), 将handler类实例化增加到OpenerDirector中
使用urllib2.install_opener()会设置urllib2的全局opener, 也可以直接调用opener.open()代替全局的urlopen方法
如果已知cookie内容, 且固定不变, 可以在header中直接添加cookie内容发送请求
headers["Cookie"] = "xxxxx" req = urllib.request.Request(url=url, headers=headers, data=req_post)
python3与python2.7部分区别:
python 3.x中urllib库和urilib2库合并为urllib库
urllib2.urlopen变为urllib.request.urlopen
urllib2.Request变为urllib.request.Request
urllib2.urlencode()变为urllib.parse.urlencode
cookielib变为http.cookiejar
相关文章推荐
- Python爬虫基础细节(urllib+cookielib+BeautifulSoup)
- Python3爬虫之urllib携带cookie爬取网页
- python爬虫get和post方法的使用以及cookie
- python爬虫之urllib.request和cookie登录CSDN
- 03—小白学Python爬虫之urllib的基本和进阶使用及Get、Post示例
- python3 urllib post json
- Python3爬虫之urllib爬取异步Ajax数据,使用post请求!
- python 爬虫好文 urllib cookie beautifulsoap
- urllib通过Post请求爬去数据并解析JSON(Python)
- python爬虫(五)_urllib2:Get请求和Post请求
- python简单爬虫(上):urllib,urllib2与cookielib三个模块
- python爬虫中get和post方法介绍以及cookie作用
- python-post-json 中文问题---微信公众号中遇到的问题
- 零基础写python爬虫之urllib2使用指南
- 零基础写python爬虫之urllib2使用指南
- Python模仿POST提交HTTP数据及使用Cookie值的方法
- Python模仿POST提交HTTP数据及使用Cookie值的方法
- 初学Python----urllib2模块与正则表达式组合而成的小爬虫
- 【用Python写爬虫】获取html的方法【四】:使用urllib下载文件
- Python 爬虫学习 urllib