如何使用 Selenium 处理 Google Authenticator

Lin*_*ino 4 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 脚本打开 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))
Run Code Online (Sandbox Code Playgroud)

我在寻找什么?

需要解决方案来使用来自谷歌身份验证器的双因素身份验证令牌。

我希望 selenium 在现有的 Firefox 浏览器实例中作为选项卡打开,我将事先登录。因此不需要登录(应该)并且可以完成“抓取”和下载。如果没有直接的方法,也许有人想出了解决方法?

我知道 selenium 无法下载文件本身,因为弹出窗口不再是浏览器的一部分。当我到达那里时,我会解决这个问题。

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

sup*_*uri 5

这是将读取谷歌身份验证器令牌并在登录中使用的代码。使用 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
Run Code Online (Sandbox Code Playgroud)