通过用户cookies访问微博首页

1.登录微博

        self.driver.delete_all_cookies()  # 删除cookies
self.driver.get(self.url)
time.sleep(2)
user = self.wait.until(EC.presence_of_element_located((By.ID,'loginName')))
pwd = self.wait.until(EC.presence_of_element_located((By.ID, 'loginPassword')))
submit = self.wait.until(EC.presence_of_element_located((By.ID, 'loginAction')))
user.send_keys(self.username)
time.sleep(1)
pwd.send_keys(self.password)
time.sleep(1)
submit.click()
time.sleep(5)

2.获取cooikes,保存json文件

cookies = self.driver.get_cookies()
cookies_dict = {}
for item in cookies:
cookies_dict[item.get('name')] = item.get('value')
with open('sina_cookies.TXT','w',encoding='utf-8') as f:
f.write(json.dumps(cookies_dict, ensure_ascii='False',indent=4))

3..读取json文件,获得cooikes,访问主页

with open('sina_cookies.TXT','r',encoding='utf-8') as f:
cooikes_dict = json.loads(f.read())
response = requests.get('https://weibo.cn/', cookies = cookies_dict, timeout=5, allow_redirects=False)
if response.status_code == 200:
print('用户cookies有效')

4.详细代码

#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/4/26 0:24
# @Author : hyang
# @File : WeiboCooikes.py
# @Software: import time
import json
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait # 等待元素加载的
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.by import By
import requests class WeiboCooikesLogin(object):
"""
通过cookies访问微博
"""
def __init__(self,username, password):
self.url = 'https://passport.weibo.cn/signin/login'
self.driver = webdriver.Chrome()
self.driver.maximize_window() # 最大化窗口
self.wait = WebDriverWait(self.driver, 6)
self.username = username
self.password = password def __del__(self):
"""
关闭浏览器
:return:
"""
print('close browser')
self.driver.close() def open_url(self):
"""
打开url登录微博
:return:
"""
self.driver.delete_all_cookies() # 删除cookies
self.driver.get(self.url)
time.sleep(2)
user = self.wait.until(EC.presence_of_element_located((By.ID,'loginName')))
pwd = self.wait.until(EC.presence_of_element_located((By.ID, 'loginPassword')))
submit = self.wait.until(EC.presence_of_element_located((By.ID, 'loginAction')))
user.send_keys(self.username)
time.sleep(1)
pwd.send_keys(self.password)
time.sleep(1)
submit.click()
time.sleep(5) def password_error(self):
"""
判断用户名密码错误
:return:
"""
try:
return self.wait.until(EC.text_to_be_present_in_element((By.ID,'errorMsg'),'用户名或密码错误'))
except TimeoutException as e:
return False def login_successful(self):
"""
获得登录成功标志
:return:
"""
try:
return self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'drop-title'))) except TimeoutException as e:
return False def process_cookies(self,cookies):
"""
处理cookies
:param cookies:
:return:
"""
cookies_dict = {}
for item in cookies:
cookies_dict[item.get('name')] = item.get('value')
return cookies_dict def save_cookies(self,cookies_dict):
"""
保存cookies
:param cookies_dict:
:return:
"""
with open('sina_cookies.TXT','w',encoding='utf-8') as f:
f.write(json.dumps(cookies_dict, ensure_ascii='False',indent=4)) def get_cookies_main(self):
self.open_url()
if self.password_error():
print('用户名或密码错误')
if self.login_successful():
print('用户登录成功')
cookies = self.driver.get_cookies()
d = self.process_cookies(cookies)
self.save_cookies(d)
print('保存用户cookies成功') def get_cooikes(self):
"""
从文件中读取cookies
:return:
"""
with open('sina_cookies.TXT','r',encoding='utf-8') as f:
cooikes_dict = json.loads(f.read()) return cooikes_dict def login_with_cookies(self, cookies_dict):
"""
通过cookies访问主页读取信息
:param cookies_dict:
:return:
"""
time.sleep(2)
response = requests.get('https://weibo.cn/', cookies = cookies_dict, timeout=5, allow_redirects=False)
if response.status_code == 200:
print('用户cookies有效')
time.sleep(1)
if '我的首页' in response.text:
print('通过cookies登录成功') def login_cookies_main(self):
print('用户开始刷新主页!!')
d = self.get_cooikes()
print('读取用户cookies!!')
self.login_with_cookies(d)
print('通过cookies访问主页!!') if __name__ == '__main__':
username = '' # 新浪微博用户
pwd = '' # 新浪微博用户密码
wb = WeiboCooikesLogin(username, pwd)
wb.get_cookies_main() # 得到cookies
wb.login_cookies_main() # 用cookies访问主页

输出结果

Python——通过用户cookies访问微博首页的更多相关文章

  1. 利用cookies+requests包登陆微博,使用xpath抓取目标用户的用户信息、微博以及对应评论

    本文目的:介绍如何抓取微博内容,利用requests包+cookies实现登陆微博,lxml包的xpath语法解析网页,抓取目标内容. 所需python包:requests.lxml 皆使用pip安装 ...

  2. python接入微博第三方API之2接入用户登录和微博发布

    python接入微博第三方API之2接入用户登录和微博发布 # coding=utf-8 import requests import json import MySQLdb from datetim ...

  3. (26)基于cookie的登陆认证(写入cookie、删除cookie、登陆后所有域下的网页都可访问、登陆成功跳转至用户开始访问的页面、使用装饰器完成所有页面的登陆认证)

    获取cookie request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age ...

  4. Servlet—Cookie(显示用户上次访问时间、显示商品浏览历史)

    1 . 什么是会话? 会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话. 1.1 会话过程中要解决的一些问题? 每个用户在使用浏览器 ...

  5. 微博API怎么爬取其它未授权用户的微博/怎么爬取指定用户公布的微博

    获取某个用户最新发表的微博列表:http://open.weibo.com/wiki/2/statuses/user_timeline 原接口已经被封.很多人都在问怎么获取指定用户的微博,于是写这篇B ...

  6. Python 中的属性访问与描述符

    在Python中,对于一个对象的属性访问,我们一般采用的是点(.)属性运算符进行操作.例如,有一个类实例对象foo,它有一个name属性,那便可以使用foo.name对此属性进行访问.一般而言,点(. ...

  7. 简单的Cooki案例——记录用户上次访问该网页的时间

    功能: 帮助网站实现提示客户端计算机上次访问网站的时间 实现原理: 将每一个会话作为一次访问过程,将每次会话的开始时间作为每次访问网站的时间,然后将这个时间以Cookie的形式存储到客户端的计算机中, ...

  8. Python中的属性访问与描述符

    Python中的属性访问与描述符 请给作者点赞--> 原文链接 在Python中,对于一个对象的属性访问,我们一般采用的是点(.)属性运算符进行操作.例如,有一个类实例对象foo,它有一个nam ...

  9. Python 3.6 抓取微博m站数据

    Python 3.6 抓取微博m站数据 2019.05.01 更新内容 containerid 可以通过 "107603" + user_id 组装得到,无需请求个人信息获取: 优 ...

随机推荐

  1. SOA的理解

    SOA架构的概念网上一大堆,笔者也没有发现一个准确.公认的定义.不过笔者在贴吧了发了一个比较好的解释,能够帮助理解: 一个产品有PC端.iOS端.Android端,有个数据查询的功能.传统的设计方法就 ...

  2. 从零开始学spring cloud(一) -------- spring cloud 简介

    1.微服务简介 1.1.单体架构 一个归档包(例如war格式)包含了应用所有功能的应用程序,我们通常称之为单体应用.架构单体应用的方法论,我们称之为单体应用架构. 缺点:1. 复杂性高以笔者经手的一个 ...

  3. 创建第一次C语言程序

    在这里我以VS2015为例,做演示.为什么要去演示怎样创建项目尼,因为我写第一个程序时,不知道该怎样用VS创建我的第一个应用程序. 第一步:打开VS环境如下 第二步:在开始出点击“新建项目”或在右上角 ...

  4. 287. Find the Duplicate Number 找出数组中的重复数字

    [抄题]: Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive ...

  5. centos7 微信安装

    安装过程如下: ,下载最新版本tar.gz压缩包 wget https://github.com/geeeeeeeeek/electronic-wechat/releases/download/V2. ...

  6. MYSQL库,表,记录的基本操作

    数据库操作 1.显示数据库 show databases; 默认数据库: mysql - 用户权限相关数据 test - 用于用户测试数据 information_schema - MySQL本身架构 ...

  7. Fabric的权限管理:Attribute-Based Access Control

    之前稍微了解过Client Identity Chaincode Library,这几天正好开始实际应用. 虽然了解过,还是发现了不少之前理解的不足,也踩了不少坑. 先列出官方介绍: https:// ...

  8. Fefora 14 源

    默认的源不能用,需要用下边的源路径. [fedora] name=Fedora $releasever - $basearch failovermethod=priority #baseurl=htt ...

  9. Django Model模型的实战操作笔记

    Model模型的实战操作笔记 1. 创建数据库和表 进入MySQL数据库创建数据库:mytest 进入数据库创建数据表:mytest_users CREATE TABLE `mytest_users` ...

  10. C#中读写INI文件

    C#中读写INI文件 c#的类没有直接提供对ini文件的操作支持,可以自己包装win api的WritePrivateProfileString和GetPrivateProfileString函数实现 ...