0


selenium保持用户登陆的方法(获取cookie和添加cookie)

获得cookie

首先在用户登陆界面手动获取用selenium点击等操作获得cookie,并保存至txt

def login():
    executable_path = 'geckodriver'
    driver = webdriver.Firefox(executable_path=executable_path)
    driver.get('xxxxxx')
    try:
        driver.find_element_by_link_text('其他方式登录').click()
        xxxxxxx
        time.sleep(20)
    except Exception as exception:
        print(f"ERROR !!! {exception}")
    time.sleep(10)
    cookies = driver.get_cookies()
    with open('cookies.txt', 'w') as the_file:
        for i in cookies:
            the_file.write(str(i))
            the_file.write('\n')
    driver.close()

实现登陆

在新链接添加cookie实现用户保持登陆

def get_html(url):
    """获取网页源代码,返回json格式."""
    headers = None
    executable_path = 'geckodriver'
    driver = webdriver.Firefox(executable_path=executable_path)
    driver.get(f'xxxxxx')
    cookies = []
    with open('cookies.txt', 'r') as the_file:
        for i_file in the_file:
            cookies.append(eval(i_file.strip()))
    for cookie in cookies:
        driver.add_cookie(cookie)
    driver.refresh()
    time.sleep(2)
标签: selenium firefox python

本文转载自: https://blog.csdn.net/liyunyang2000/article/details/130011787
版权归原作者 有洁癖的懒羊羊 所有, 如有侵权,请联系我们删除。

“selenium保持用户登陆的方法(获取cookie和添加cookie)”的评论:

还没有评论