如何使用硒处理Google身份验证器

时间:2019-04-26 15:12:52

标签: python selenium selenium-webdriver

我需要从Sellercentral.amazon.de下载大量的excel文件(估计:500-1000)。手动下载不是一种选择,因为每次下载都需要单击几下,直到Excel弹出。

由于亚马逊无法为我提供具有其结构的简单xml,因此我决定自行进行自动化。首先想到的是Selenium和Firefox。

问题:

需要登录到Sellercentral以及2要素认证(2FA)。因此,如果我登录一次,则可以打开另一个选项卡,输入Sellercentral.amazon.de并立即登录。 我什至可以打开浏览器的另一个实例,并立即在该实例中登录。他们可能正在使用会话cookie。 “抓取”的目标URL为https://sellercentral.amazon.de/listing/download?ref=ag_dnldinv_apvu_newapvu

但是,当我使用selenium webdrive从python-script打开URL时,将启动浏览器的新实例,但我没有登录。即使在同一时间,也有运行firefox的实例,我已经登录了。所以我想selenium启动的实例有些不同。

我尝试过的事情:

我尝试在第一个.get()之后设置一个时间延迟(以打开网站),然后我将手动登录,然后重做.get(),这将使脚本永久运行。

from selenium import webdriver
import time


browser = webdriver.Firefox()

# Wait for website to fire onload event
browser.get("https://sellercentral.amazon.de/listing/download?ref=ag_dnldinv_apvu_newapvu")

time.sleep(30000)

browser.get("https://sellercentral.amazon.de/listing/download?ref=ag_dnldinv_apvu_newapvu")

elements = browser.find_elements_by_tag_name("browse-node-component")


print(str(elements))

我在找什么?

需要使用Google身份验证器的两因素身份验证令牌的解决方案。

我希望在firefox浏览器的现有实例中将硒作为选项卡打开,我已经在此处进行了预先登录。因此,无需登录(应该),并且可以进行“抓取”和下载。 如果没有直接的方法,也许有人想出一种解决方法?

我知道硒不能下载文件本身,因为弹出窗口不再是浏览器的一部分。我到那里时会解决的。

重要说明: Firefox不是给定的!我很乐意接受任何浏览器的解决方案。

1 个答案:

答案 0 :(得分:0)

这是将读取Google身份验证器令牌并在登录中使用的代码。使用js打开新标签页。 在运行测试代码之前,先安装pyotp软件包。

  

pip安装pyotp

测试代码:

from pyotp import *
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Firefox()
driver.get("https://sellercentral.amazon.de/listing/download?ref=ag_dnldinv_apvu_newapvu")
wait = WebDriverWait(driver,10)
# enter the email
email = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@name='email']")))
email.send_keys("email goes here")

# enter password
driver.find_element_by_xpath("//input[@name='password']").send_keys("password goes here")

# click on signin button
driver.find_element_by_xpath("//input[@id='signInSubmit']").click()

#wait for the 2FA feild to display
authField = wait.until(EC.presence_of_element_located((By.xpath, "xpath goes here")))
# get the token from google authenticator
totp = TOTP("secret goes here")
token = totp.now()
print (token)
# enter the token in the UI
authField.send_keys(token)
# click on the button to complete 2FA
driver.find_element_by_xpath("xpath of the button goes here").click()
# now open new tab
driver.execute_script("""window.open("https://sellercentral.amazon.de/listing/download?ref=ag_dnldinv_apvu_newapvu")""")
# continue with your logic from here
相关问题