吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1069|回复: 0
收起左侧

[讨论] selenium 练习带cookie免验证登录 (小试文库)

[复制链接]
lihu5841314 发表于 2021-7-25 17:37
[Asm] 纯文本查看 复制代码
from selenium import webdriver
import time
import json


def browser_initial():
    """"
    进行浏览器初始化
    """
    browser= webdriver.Chrome(executable_path=r'C:\Program Files\Google\Chrome\Application\chromedriver.exe') # 调用Chrome 驱动,生成浏览器对象
    log_url = 'https://www.baidu.com'
    return log_url, browser


def get_cookies(log_url, browser):
    """
    获取cookies保存至本地
    """
    browser.get(log_url)
    time.sleep(25)  # 进行扫码
    dictCookies = browser.get_cookies()  # 获取list的cookies
    print(dictCookies)
    jsonCookies = json.dumps(dictCookies)  # 转换成字符串保存

    with open('damai_cookies.txt', 'w') as f:
        f.write(jsonCookies)
    print('cookies保存成功!')


if __name__ == "__main__":
    tur = browser_initial()
    get_cookies(tur[0], tur[1])
#-------------------------------------------------------------------------------------
from  selenium import   webdriver
from  selenium.webdriver.common.by import By
from  selenium.webdriver.support.wait import WebDriverWait
import selenium.webdriver.support.expected_conditions as EC
import time ,json,os


url = 'https://wenku.baidu.com/view/31b87809ab8271fe910ef12d2af90242a995ab45.html'
def log_cokie(browser):
    """
    从本地读取cookies并刷新页面,成为已登录状态
    """
    os.chdir('F:\\pythonwork')
    with open('damai_cookies.txt', 'r', encoding='utf8') as f:
        listCookies = json.loads(f.read())
        print(listCookies)
    browser.get('https://www.baidu.com')
    for cookie in listCookies:
        print(cookie)
        browser.add_cookie(cookie)
    browser.refresh()  # 刷新网页,cookies才成功
log_cokie(browser)

try:
    browser.get(url)
    print(browser.get_cookies())
    Cl = browser.find_element(By.CSS_SELECTOR,".fold-page-text")
    browser.execute_script('arguments[0].click();',Cl)   #被检测到了不准点击  点击后把元素停换成了别的元素
    time.sleep(5)  #被遮挡了
    for  i  in range(1,4):
        browser.execute_script(f'window.scrollTo(0,document.body.scrollHeight*{i/3})')
        time.sleep(3)
    Cls = browser.find_elements(By.CLASS_NAME,"dialog-container")
    for  cl2  in  Cls:
        try:
             Cl2 = cl2.find_element_by_tag_name('i')
             browser.execute_script('arguments[0].click();',Cl2)   #被检测到了不准点击  点击后把元素停换成了别的元素
             time.sleep(3)
        except:
            continue
    time.sleep(5)
    pays = browser.find_elements(By.CLASS_NAME,'ie-fix')
    print(len(pays))
    for pay  in  pays:
        print(pay.text)
        with open('python_items.txt','a')  as  f:
             f.write(pay.text)
    time.sleep(60)

    print("over")
finally:
    browser.close()

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-26 00:40

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表