Chromedriver用Python拾取现有的Chrome浏览器会话

时间:2018-02-08 06:52:50

标签: python selenium selenium-chromedriver

我想在一个浏览器的网站下打开几个网页链接(几个标签页)。该网站需要登录名和密码。

当登录密码和密码时,它会转到验证页面,询问通过电子邮件发送给我的验证码。

我检查了电子邮件并在验证页面上输入验证码。登录成功。

现有的浏览器就在我面前。

然而,代码没有提取,并打开另一个选项卡。似乎某个连接丢失了。

我该如何继续? (或者作为替代方案,Python如何重用现有的Chrome浏览器?)

代码通常效果很好,但是遇到这种情况(登录,输入验证码),它没有。

import os, time
from selenium.webdriver import ChromeOptions, Chrome
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

chromedriver = "C:\\Python27\\Scripts\\chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver

opts = ChromeOptions()                                         # leave browser open after code
opts.add_experimental_option("detach", True)                   # leave browser open after code
opts.add_argument('disable-infobars')
driver = webdriver.Chrome(chromedriver, chrome_options=opts)  # leave browser open after code

driver.maximize_window()

verificationErrors = []
accept_next_alert = True

time.sleep(5)

base_url = "https://awebsite.com/"
driver.get(base_url)
window_0 = driver.window_handles[0]
driver.switch_to_window(window_0)
driver.find_element_by_id("username").clear()
driver.find_element_by_id("username").send_keys("username")
driver.find_element_by_id("password").clear()
driver.find_element_by_id("password").send_keys("password")
driver.find_element_by_id("Submit").click()

time.sleep(60)

driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
window_1 = driver.window_handles[1]
driver.switch_to_window(window_1)
time.sleep(3)
driver.get('https://anotherwebsite.com')
time.sleep(3)

sys.exit()

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法在两个不同的页面/标签上执行某些操作:

# Handle base page
base_url = "https://awebsite.com/"
driver.get(base_url)
window_0 = driver.current_window_handle
...

# Handle new page
driver.execute_script('window.open("https://anotherwebsite.com");')
window_1 = [window for window in driver.window_handles if window != window_0][0]
driver.switch_to_window(window_1)
# driver.close() # To close new tab
...

# Switch back to base page
driver.switch_to_window(window_0)