gpt4 book ai didi

python - 如何使用 Selenium 处理 Google Authenticator

转载 作者:太空宇宙 更新时间:2023-11-04 04:13:43 25 4
gpt4 key购买 nike

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

由于亚马逊无法为我提供一个简单的 xml 及其结构,我决定自己将其自动化。首先想到的是 Selenium 和 Firefox。

问题:

需要登录卖家中心,以及双因素身份验证 (2FA)。因此,如果我登录一次,我可以打开另一个选项卡,输入 sellercentral.amazon.de 并立即登录。我什至可以打开浏览器的另一个实例,并立即登录。他们可能正在使用 session 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))

我在找什么?

需要解决方案以使用来自 google 身份验证器的双因素身份验证 token 。

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

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

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

最佳答案

这是将读取谷歌验证器 token 并在登录中使用的代码。使用js打开新标签页。在运行测试代码之前安装pyotp包。

pip install 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

关于python - 如何使用 Selenium 处理 Google Authenticator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55870489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com