动态获取cookie 进行数据的爬取

import requests,json
from urllib import request,parse

这个包是用来保存cookie的

import hashlib
from http import cookiejar
def md5_password(password_str):
#创建加密对象
MD5=hashlib.md5()
password_bytes=password_str.encode(encoding=’utf-8’)
MD5.update(password_str)
result=MD5.hexdigest()
return result

定义函数并传入参数 其中密码为字符串

def renren(phone,password_str):
#动态获取cookie
#(1)创建一个对象用于存储cookie 相当于一个容器
cookie=cookiejar.CookieJar()
#这是一个操作 相当于获取到cookie 之后再存放到对象之中只是一个执行的过程
handler=request.HTTPCookieProcessor(cookie)
#opener 用于检测是否有cookie 和cookie 是否更新了 如果更新了那么调用handler 函数用于把请求到的数据放到cookie对象之中
opener=request.build_opener(handler)
#另外 urlopen对象是一个封装好的函数
#request.urlopen()等价于request.build().open(), urlopen()函数中如果有cookie 就不能用urlopen()了只能分两步来写了
url=’http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=201875165627
password_md5_str=md5_password(password_str)
form={
‘email’:str(phone),
‘icode’:”,
‘origURL’:’http://www.renren.com/home‘,
‘domain’:’renren.com’,
‘key_id’:’1’,
‘captcha_type’:’web_login’,
‘password’:password,
‘rkey’:password_md5_str,
‘f’:’https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DCGacXA42jMDrC5zTEqjBuM9YrUe_wAOIITgOzj1MjHi%26wd%3D%26eqid%3D8df8329f00011ce3000000035b768118’,
}
#讲字典格式的数据转化为字符串
form_str=parse.urlencode(form)
#把字符串转化为二进制类型的数据
form_bytes=form_str.encode(‘utf-8’)
#把URL和form的二进制传入到from中获取响应到的数据
response=opener.open(url,form_bytes)
#把相应的内容解析成bytes
html_bytes=response.read()
#把bytes转化为html_str
html_str=html_bytes.decode(‘utf-8’)
#把html_str 转化为dict
html_dict=json.loads(html_str)
#获取连接
home_url=html_dict[‘homeUrl’]
#通过连接获取相应到的数据
response_home=opener.open(home_url)
#把获取到的数据解析成bytes
html_home_str=response_home.read()
return html_home_str
if name==’main‘:
phone=xxxx
password=’xxxx’
s=renren(phone,password)
with open(‘renren.html’,’wb’) as ff:
ff.write(s)

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值