代码拉取完成,页面将自动刷新
#Users/zhongsheng/Library/Application Support/Google/Chrome/Default
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
import pickle
import requests
# def save_cookies()
def login_auto(login_url, username, password,
username_xpath, password_xpath,
submit_xpath, cookies_file, browser=None):
if browser is None:
options = webdriver.ChromeOptions()
# chrome在系统PATH时,可以不指定 binary_location
options.binary_location = '/usr/bin/google-chrome'
options.add_argument('headless')
options.add_argument('window-size=1200x600')
browser = webdriver.Chrome(ChromeDriverManager().install())
browser.maximize_window()
browser.get(login_url)
time.sleep(9) # 等登录加载完成
browser.find_element_by_xpath(username_xpath).send_keys(username)
browser.find_element_by_xpath(password_xpath).send_keys(password)
browser.find_element_by_xpath(submit_xpath).click()
time.sleep(9) # 等登录加载完成
cookies = browser.get_cookies()
print(cookies)
save_cookies(cookies, cookies_file)
def login_manually(login_url, cookies_file, browser=None):
# 既然是手动,这里就不自动填写用户名和密码了
if browser is None:
browser = webdriver.Chrome(ChromeDriverManager().install())
browser.get(login_url)
time.sleep(30) # 给自己多了点时间输入用户名、密码、验证码
cookies = browser.get_cookies()
print(cookies)
save_cookies(cookies, cookies_file)
def load_to_browser(cookies_file, browser=None):
with open(cookies_file, 'rb') as f:
cookies = pickle.load(f)
if browser is None:
browser = webdriver.Chrome(ChromeDriverManager().install())
for cookie in cookies:
browser.add_cookie(cookie)
return browser
def load_to_requests(cookies_file, session=None):
with open(cookies_file, 'rb') as f:
cookies = pickle.load(f)
if session is None:
session = requests.Session()
for cookie in cookies:
session.cookies.set(cookie['name'], cookie['value'])
def save_cookies(requests_cookiejar, filename):
with open(filename, 'wb') as f:
pickle.dump(requests_cookiejar, f)
login_url = 'https://pan.baidu.com/'
username_xpath = '//input[@id="TANGRAM__PSP_4__userName"]'
password_xpath = '//input[@id="TANGRAM__PSP_4__password"]'
submit_xpath = '//input[@id="TANGRAM__PSP_4__submit"]'
username = '15611658186'
password = '1986630tian168'
login_auto(login_url, username, password, username_xpath, password_xpath, submit_xpath, 'z-baidu.cookies')
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。