python爬虫-urllib+cookie+json+POST

本文介绍如何使用Python的urllib库实现带有Cookie和JSON数据的POST请求。通过具体代码示例展示了如何构造请求头、处理Cookie及发送POST请求,并提供了一些关于urllib库的基本使用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接: python爬虫-urllib+cookie+json+POST

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

发送json, 去掉headers['Content-Type'] = 'application/json'注释即可

相关知识:
  1. 默认的urllib.request.urlopen()不带cookie信息
  2. urlopen是一个封装好的OpenerDirector实例,参数为(url, data, timeout)
  3. 通过build_opener可以创建OpenerDirector实例, build_opener(*handlers), 将handler类实例化增加到OpenerDirector中
  4. 使用urllib2.install_opener()会设置urllib2的全局opener, 也可以直接调用opener.open()代替全局的urlopen方法
  5. 如果已知cookie内容, 且固定不变, 可以在header中直接添加cookie内容发送请求
headers["Cookie"] = "xxxxx"
req = urllib.request.Request(url=url, headers=headers, data=req_post)
  • 1
  • 2
  1. 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值