看这篇文章以前你们能够先看下个人上一篇文章:cookies详解python
本篇咱们就针对上一篇来讲一下cookies的基本应用web
使用selenium模拟登录百度
from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.wait import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom PIL import Image
chrome_option = webdriver.ChromeOptions()
chrome_path = "/usr1/webdrivers/chromedriver"def login_baidu():
driver = None
try:
driver = webdriver.Chrome(executable_path=chrome_path)
driver.get("https://www.baidu.com")
print(driver.title)
WebDriverWait(driver, 10, 0.5).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="u1"]/*[@class="lb"]')))
element = driver.find_element_by_xpath('//*[@id="u1"]/a[7]')
element.click()
WebDriverWait(driver, 10, 0.5).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="TANGRAM__PSP_10__footerULoginBtn"]')))
element = driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__footerULoginBtn"]')
element.click()
WebDriverWait(driver, 10, 0.5).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="TANGRAM__PSP_10__userName"]')))
element = driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__userName"]')
element.send_keys("18091734136")
WebDriverWait(driver, 10, 0.5).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="TANGRAM__PSP_10__password"]')))
element = driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__password"]')
element.send_keys("wuqxxxxx89")
WebDriverWait(driver, 10, 0.5).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="TANGRAM__PSP_10__verifyCodeImg"]')))
element = driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__verifyCodeImg"]')
driver.get_screenshot_as_file("qrcode.png")
image = Image.open("qrcode.png")
left = element.location.get("x")
top = element.location.get("y")
right = left + element.size.get("width")
bottom = top + element.size.get("height")
cropImg = image.crop((left, top, right, bottom))
cropImg.save("code.png")
yanzheng = input(">>>")
WebDriverWait(driver, 10, 0.5).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="TANGRAM__PSP_10__verifyCode"]')))
element = driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__verifyCode"]')
element.send_keys(yanzheng)
WebDriverWait(driver, 10, 0.5).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="TANGRAM__PSP_10__submit"]')))
element = driver.find_element_by_xpath('//*[@id="TANGRAM__PSP_10__submit"]')
element.click() # 若是须要手机验证码
try:
WebDriverWait(driver, 10, 0.5).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="TANGRAM__36__button_send_mobile"]')))
element = driver.find_element_by_xpath('//*[@id="TANGRAM__36__button_send_mobile"]')
element.click()
WebDriverWait(driver, 10, 0.5).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="TANGRAM__36__input_vcode"]')))
element = driver.find_element_by_xpath('//*[@id="TANGRAM__36__input_vcode"]')
duanxin = input(">>>")
element.send_keys(duanxin)
WebDriverWait(driver, 10, 0.5).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="TANGRAM__36__button_submit"]')))
element = driver.find_element_by_xpath('//*[@id="TANGRAM__36__button_submit"]')
element.click() except Exception as e:
print(e)
driver.get_screenshot_as_file("screen.png") finally:
print("关闭") if driver:
driver.quit()
selenium操做很简单,这里不作详解讲解,之后咱们开爬虫基础系列文章的时候会讲到。chrome
selenium保存cookies
cookies = driver.get_cookies()with open("cookies.txt", "w") as fp:
json.dump(cookies, fp)
这里切记,若是咱们要使用json.load读取数据,那么必定要使用json.dump来写入数据,不能使用str(cookies)直接转为字符串进行保存,由于其存储格式不一样。这样咱们就将cookies保存在文件中了。数据库
selenium读取cookies
def read_cookies():
# 设置cookies前必须访问一次百度的页面
driver.get("http://www.baidu.com") with open("cookies.txt", "r") as fp:
cookies = json.load(fp) for cookie in cookies: # cookie.pop('domain') # 若是报domain无效的错误
driver.add_cookie(cookie)
driver.get("http://www.baidu.com")
这里不用登陆就会直接显示个人用户名。并且要注意不一样的浏览器可能处理方式不一样,好比在火狐浏览器中就会报错:selenium.common.exceptions.InvalidCookieDomainException: Message: .baidu.com,若是碰到这种错误(不必定,也可能跟系统、浏览器都有关系),在add_cookie的时候咱们能够把domain去掉就好了。json
requests读取cookies
import requestsfrom requests.cookies import RequestsCookieJar
s = requests.session()
s.verify = False
s.headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"
}
s.get("http://www.baidu.com")#这里咱们使用cookie对象进行处理jar = RequestsCookieJar()with open("cookies.txt", "r") as fp:
cookies = json.load(fp) for cookie in cookies:
jar.set(cookie['name'], cookie['value'])#百度我的中心r = s.get("https://www.baidu.com/p/setting/profile/basic", cookies=jar)# 也可使用字典设置cookies_dict = dict()with open("cookies.txt", "r") as fp:
cookies = json.load(fp) for cookie in cookies:
cookies_dict[cookie['name']] = cookie['value']
r = s.get("https://www.baidu.com/p/setting/profile/basic", cookies=cookies_dict)
r.encoding = "utf-8"print(r.text)
requests库可使用cookies对象和dict对象来指定cookies,这个能够看一下源码浏览器
经过requests读取cookies的使用,咱们知道在cookies中咱们通常只使用name和value,像domain、path等值都是不须要使用的,并且上面传入cookies字典的例子咱们知道,只要保存了cookies中的name和value,不管你以什么样的方式保存,文件、或者数据库等,最后读取出来只要生成对应的字典格式就好了。服务器
requests保存cookies
import requests
s = requests.session()
s.verify = Falses.headers = { "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"
}# 这里能够是模拟登录的步骤s.get("http://www.baidu.com")
cookies = requests.utils.dict_from_cookiejar(s.cookies)with open("cook.txt", "w") as fp:
json.dump(cookies, fp)
print(cookies)
首先咱们看一下requests.session里面的cookies,它是一个RequestsCookieJar对象,这就是咱们在上面使用的时候用RequestsCookieJar对象读取cookies的缘由了微信
下面咱们看到requests.utils.dict_from_cookiejar方法,这是requests库提供的一个方法,把上面的RequestsCookieJar对象转换为一个字典(字典里只有name和value),这就是我上面说的,requests库只使用name和value值,而咱们selenium中保存的cookies中包含domain、path等信息。cookie
另外还有一个方法requests.utils.cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True)这个方法,根据字典生成一个RequestsCookieJar对象,为何须要这样一个方法呢,可能在上面的应用中有些人会有疑问,咱们的cookies是经过get/post方法的参数传进去的,那么在访问其余网页的时候都要去传递这样一个参数吗?这样很不方便并且容易遗忘。看上图的s.cookies变量,它是requests.session对象中的变量,并且是一个RequestsCookieJar类型的对象,那么咱们就可使用这个函数把读取的字典信息转换为RequestsCookieJar对象,而后把值直接设置给s.cookies,就像上面代码里的headers同样,这样就方便不少了吧。session
上面我都是将cookies值保存在文件中,在大多数状况下咱们通常使用都是将其保存在数据库中,启动一个服务器专门进行登陆验证并保存cookies值。后面我会写一篇Flask+Redis进行cookies池维护的文章。
若是你以为个人文章还能够,能够关注个人微信公众号,查看更多实战文章:Python爬虫实战之路
也能够扫描下面二维码,添加个人微信公众号
本文分享自微信公众号 - python爬虫实战之路(small_bud1989)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。