目录
获得cookie
实现登陆
获得cookie
首先在用户登陆界面手动获取用selenium点击等操作获得cookie,并保存至txt文章来源:https://www.toymoban.com/news/detail-505676.html
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实现用户保持登陆文章来源地址https://www.toymoban.com/news/detail-505676.html
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保持用户登陆的方法(获取cookie和添加cookie)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!