Python——通过用户cookies访问微博首页
通过用户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访问微博首页的更多相关文章
- 利用cookies+requests包登陆微博,使用xpath抓取目标用户的用户信息、微博以及对应评论
本文目的:介绍如何抓取微博内容,利用requests包+cookies实现登陆微博,lxml包的xpath语法解析网页,抓取目标内容. 所需python包:requests.lxml 皆使用pip安装 ...
- python接入微博第三方API之2接入用户登录和微博发布
python接入微博第三方API之2接入用户登录和微博发布 # coding=utf-8 import requests import json import MySQLdb from datetim ...
- (26)基于cookie的登陆认证(写入cookie、删除cookie、登陆后所有域下的网页都可访问、登陆成功跳转至用户开始访问的页面、使用装饰器完成所有页面的登陆认证)
获取cookie request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age ...
- Servlet—Cookie(显示用户上次访问时间、显示商品浏览历史)
1 . 什么是会话? 会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话. 1.1 会话过程中要解决的一些问题? 每个用户在使用浏览器 ...
- 微博API怎么爬取其它未授权用户的微博/怎么爬取指定用户公布的微博
获取某个用户最新发表的微博列表:http://open.weibo.com/wiki/2/statuses/user_timeline 原接口已经被封.很多人都在问怎么获取指定用户的微博,于是写这篇B ...
- Python 中的属性访问与描述符
在Python中,对于一个对象的属性访问,我们一般采用的是点(.)属性运算符进行操作.例如,有一个类实例对象foo,它有一个name属性,那便可以使用foo.name对此属性进行访问.一般而言,点(. ...
- 简单的Cooki案例——记录用户上次访问该网页的时间
功能: 帮助网站实现提示客户端计算机上次访问网站的时间 实现原理: 将每一个会话作为一次访问过程,将每次会话的开始时间作为每次访问网站的时间,然后将这个时间以Cookie的形式存储到客户端的计算机中, ...
- Python中的属性访问与描述符
Python中的属性访问与描述符 请给作者点赞--> 原文链接 在Python中,对于一个对象的属性访问,我们一般采用的是点(.)属性运算符进行操作.例如,有一个类实例对象foo,它有一个nam ...
- Python 3.6 抓取微博m站数据
Python 3.6 抓取微博m站数据 2019.05.01 更新内容 containerid 可以通过 "107603" + user_id 组装得到,无需请求个人信息获取: 优 ...
随机推荐
- cdnbest配置强制ssl跳转
如何配置强制ssl跳转 1. 登陆用户站点,点击下图图标: 2. 如下图添加证书和开启强制ssl即可 hsts解释和作用: 国际互联网工程组织IETF正在推行一种新的Web安全协议HTTP Stric ...
- springboot 整合 mybatis
spirngboot 整合mybatis有两种方式 第一种 无配置文件注解版,这一种符合springboot的风格 第二种 有配置文件xml版本,这一种就是传统的模式 无论哪一种,首先都需要加入MyS ...
- Linux 下监控用户最大进程数参数(nproc)是否到达上限的步骤:
https://www.cnblogs.com/autopenguin/p/6184886.html 1.查看各系统用户的进程(LWP)数: 注意:默认情况下采用 ps 命令并不能显示出所有的进程.因 ...
- 大数据OLAP引擎对比
Presto:内存计算,mpp架构 PB级别数据 presto适合pb级的海量数据查询分析,不是说把pb的数据放进内存,比如一张pb表,查询count,vag这种有个特点,虽然数据很多,但是最终的 ...
- [leetcode]152. Maximum Product Subarray最大乘积子数组
Given an integer array nums, find the contiguous subarray within an array (containing at least one n ...
- [leetcode]30. Substring with Concatenation of All Words由所有单词连成的子串
You are given a string, s, and a list of words, words, that are all of the same length. Find all sta ...
- [leetcode]41. First Missing Positive第一个未出现的正数
Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2, ...
- 优化linux,安装node环境
就是这样我的心爱的云主机就被攻击了,反正我是很久没宠幸过她,肯定不是我去攻击人家,但是吧昨天就突然来了封邮件,小白一个查不出什么,用了 netsat -na显示所有连接到服务器的活跃的网络连接数,发现 ...
- javaweb开发.页面中文乱码问题
1.设置eclips , window->Preferences->web->JSP Files中的Encoding选项为UTF-8 2.修改jsp文件头部为UTF-8 <%@ ...
- python 的面相对象编程--对应c++
在python的面相对象编程中,我们常常在class中可以看到a(), _b() , __c(), __d()__这样的函数. 由于我是看廖雪峰老师的教程,廖老师为了简单起见,没有引入太多概念,我 ...