如何使用Python2.7中自动登录脚本中浏览器保存的凭据?

2024-06-13 02:11:59 发布

您现在位置:Python中文网/ 问答频道 /正文

当我手动打开一个浏览器,包括firefox和chrome,然后转到一个网站,在那里我以前通过浏览器保存了我的登录凭据,用户名和密码字段会自动填充。但是,当我使用python selenium webdriver打开特定页面的浏览器时,字段不会填充。

我的脚本的要点是打开网页并使用element.submit()登录,因为登录凭据应该已经填充,但不是。 我怎样才能让它们在字段中填充?

例如:

driver = webdriver.Chrome()    
driver.get("https://facebook.com")    
element = driver.find_element_by_id("u_0_v")    
element.submit()

Tags: 脚本密码网站driverselenium浏览器页面element
2条回答
from selenium import webdriver
from os.path import abspath
from os import path
from time import sleep

options = webdriver.ChromeOptions()
options.add_argument(r"--user-data-dir=C:\...")  # Path to your chrome profile or you can open chrome and type: "chrome://version/" on URL

chrome_driver_exe_path = abspath("./chromedriver_win32/chromedriver.exe")  # download from https://chromedriver.chromium.org/downloads
assert path.exists(chrome_driver_exe_path), 'chromedriver.exe not found!'
web = webdriver.Chrome(executable_path=chrome_driver_exe_path, options=options)

web.get("https://www.google.com")
web.set_window_position(0, 0)
web.set_window_size(700, 700)
sleep(2)
web.close()

这是因为selenium不使用默认的浏览器实例,它会打开一个带有临时(空)配置文件的不同实例。

如果希望它加载默认配置文件,则需要指示它这样做。

下面是一个chrome示例:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = webdriver.ChromeOptions() 
options.add_argument("user-data-dir=C:\\Path") #Path to your chrome profile
w = webdriver.Chrome(executable_path="C:\\Users\\chromedriver.exe", chrome_options=options)

下面是一个firefox的例子:

from selenium import webdriver
from selenium.webdriver.firefox.webdriver import FirefoxProfile

profile = FirefoxProfile("C:\\Path\\to\\profile")
driver = webdriver.Firefox(profile)

接下来,我们在(非官方的)文档中找到了一个链接。Firefox Profile而Chrome驱动程序信息就在它下面。

相关问题 更多 >