如何使用Selenium处理Google验证器

2024-09-30 10:29:46 发布

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

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

由于amazon不能为我提供一个简单的xml结构,所以我决定自己将其自动化。首先想到的是Selenium和Firefox。在

问题:

需要登录到sellercentral以及2-factor-authentication(2FA)。因此,如果我登录一次,我可以打开另一个选项卡,输入sellercentral.amazon.de我马上就登录了。 我甚至可以打开浏览器的另一个实例,并立即在那里登录。他们可能正在使用会话cookie。“scrape”的目标URL是https://sellercentral.amazon.de/listing/download?ref=ag_dnldinv_apvu_newapvu。在

但是,当我用selenium webdrive从python脚本打开URL时,会启动一个新的浏览器实例,在这个实例中我没有登录。尽管如此,有一些firefox实例同时运行,我在其中登录。所以我想selenium启动的实例有些不同。在

我尝试过的:

我尝试在第一个.get()之后设置一个timedelay(打开站点),然后手动登录,然后重新执行.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))

我在找什么?

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

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

我知道selenium本身无法下载文件,因为弹出窗口不再是浏览器的一部分。我到那儿后会修好的。在

重要提示: 火狐不是一个给定的!我很乐意接受任何浏览器的解决方案。在


Tags: 实例httpsbrowserrefamazongetdownloadselenium
1条回答
网友
1楼 · 发布于 2024-09-30 10:29:46

下面是将读取googleauthenticator令牌并在登录中使用的代码。使用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

相关问题 更多 >

    热门问题