python利用selenium获取cookies实现免登录 (~实例百度贴吧~)


  • selenium简介、用法参考

  • python+selenium+firefox的环境搭建

    1. 在此我使用的是 python:Anaconda2(python2.7)
    2. selenium的安装 pip install -U selenium
    3. Firefox驱动的下载

    1、下载geckodriver.exe
    请根据系统版本选择下载;(如Windows 64位系统)
    2、下载解压后将getckodriver.exe复制到Firefox的安装目录下,如(C:\Program Files\Mozilla Firefox),
    并在环境变量Path中添加路径

  • 代码实现

# -*-coding:utf-8 -*-
from selenium import webdriver


d = webdriver.Firefox()
d.get("https://tieba.baidu.com/index.html")

# 登陆
ele_login = d.find_element_by_css_selector(
    '.u_login > div:nth-child(1) > a:nth-child(1)')
ele_login.click()

# 处理表单输入框
ele_username = d.find_element_by_css_selector('#TANGRAM__PSP_8__userName')
ele_username.clear()
ele_username.send_keys('用户名')
ele_passwd = d.find_element_by_css_selector('#TANGRAM__PSP_8__password')
ele_passwd.clear()
ele_passwd.send_keys('密码')
ele_submit = d.find_element_by_css_selector('#TANGRAM__PSP_8__submit')
ele_submit.click()

# 查看并保存cookies
cookies = [item["name"] + "=" + item["value"] for item in d.get_cookies()]
cookiesStr = ' '.join(cookies)
# print cookiesStr
with open('cookies.txt', 'w') as f:
    f.write(cookiesStr)

# 验证cookies
# 法一:使用requests库
# 将cookies存为字典视图
with open('cookies.txt') as f:
    str_cookies = f.read()
list_cookies = str_cookies.split(' ')
cookies = {}
for cookie in list_cookies:
    key = c.split('=')[0]
    value = c.split('=')[-1]
    cookies.update({key : value})

url = 'https://tieba.baidu.com/index.html'
r = requests.get(url, cookies=cookies)
print r.status_code

你可能感兴趣的:(python利用selenium获取cookies实现免登录 (~实例百度贴吧~))