本帖最后由 vsyour 于 2019-7-19 11:33 编辑
有了cookie网站就不需要登陆了。
对于那些有验证码的网站利用cookie登陆还是一个比较省时省力的办法。
代码如下:
[Python] 纯文本查看 复制代码 # coding:utf-8
from fake_useragent import UserAgent
from selenium import webdriver
from bs4 import BeautifulSoup
import time
import datetime
ua = UserAgent()
def kanxue_Chrome():
loginUrl = r'https://passport.kanxue.com/user-login.htm'
# 进入浏览器设置
options = webdriver.ChromeOptions()
# 设置中文
options.add_argument('lang=zh_CN.UTF-8')
# 更换头部
useragent = ua['google chrome']
options.add_argument('"%s"' % useragent)
browser = webdriver.Chrome(chrome_options=options,executable_path=r'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe')
browser.get(loginUrl)
time.sleep(50) # 程序走到这里时暂停,登陆网页后得到cookie
print('cookie:-->start'.center(130, '*'))
for cookie in browser.get_cookies():
#print("%s -> %s" % (cookie['name'], cookie['value']))
tip='''browser.add_cookie({'name': '%s', 'value': '%s'})'''% (cookie['name'],cookie['value'])
print(tip)
print('cookie:-->End'.center(130, '*'))
# 将生成的cookies 直接加入就行了
if __name__ == '__main__':
kanxue_Chrome()
20190719 更新
[Python] 纯文本查看 复制代码 # coding:utf-8
'''
获取网站cookie信息
'''
from selenium import webdriver
import time
# from fake_useragent import UserAgent
# ua = UserAgent()
class GetCookie:
def __init__(self):
pass
def chrome(self, url):
# 进入浏览器设置
# options = webdriver.ChromeOptions()
# 设置中文
# options.add_argument('lang=zh_CN.UTF-8')
# options.add_argument('lang=en_US.UTF-8')
# 更换头部
# useragent = ua['google chrome']
# options.add_argument('"%s"' % useragent)
# browser = webdriver.Chrome(chrome_options=options,executable_path=r'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe')
browser = webdriver.Chrome(
executable_path=r'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe')
browser.get(url)
time.sleep(20) # 程序走到这里时暂停,登陆网页后得到cookie
print('cookie:-->start'.center(130, '*'))
for cookie in browser.get_cookies():
# print("%s -> %s" % (cookie['name'], cookie['value']))
tip = '''browser.add_cookie({'name': '%s', 'value': '%s'})''' % (cookie['name'], cookie['value'])
print(tip)
print('cookie:-->End'.center(130, '*'))
# 将生成的cookies 直接加入就行了
def firefox(self, url):
browser = webdriver.Firefox(executable_path=r'C:\Anaconda3\geckodriver.exe')
browser.get(url)
time.sleep(20) # 程序走到这里时暂停,登陆网页后得到cookie
print('cookie:-->start'.center(130, '*'))
for cookie in browser.get_cookies():
# print("%s -> %s" % (cookie['name'], cookie['value']))
tip = '''browser.add_cookie({'name': '%s', 'value': '%s'})''' % (cookie['name'], cookie['value'])
print(tip)
print('cookie:-->End'.center(130, '*'))
if __name__ == '__main__':
# 实例化
getCookie = GetCookie()
# 用chrome获取cookie
#getCookie.chrome('https://www.taobao.com')
# 用 firefox 获取cookie
getCookie.firefox('https://www.taobao.com')
|