我如何 "click" 在 python 中下载 selenium 上的按钮

How can I "click" download button on selenium in python

我想使用爬虫下载有关 Google 分析的用户数据,所以我使用 selenium 编写了一些代码。但是,我无法单击 "export" 按钮。它总是显示错误 "no such element"。我尝试使用 find_element_by_xpath、by_name 和 by_id。 我在下面上传了 GA 页面的检查。

我试过了:

 driver.find_element_by_xpath("//*[@class='download-link']").click()
    driver.find_element_by_xpath('//*[@id="ID-activity-userActivityTable"]/div/div[2]/span[6]/button')
    driver.find_element_by_xpath('//*[@class='_GAD.W_DECORATE_ELEMENT.C_USER_ACTIVITY_TABLE_CONTROL_ITEM_DOWNLOAD']')

Python代码:

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.Chrome('/Users/parkjunhong/Downloads/chromedriver')
driver.implicitly_wait(3)
usrid = '1021'
url = 'https://analytics.google.com/analytics/web/#/report/app-visitors-user-activity/a113876882w169675624p197020837/_u.date00=20190703&_u.date01=20190906&_r.userId='+usrid+'&_r.userListReportStates=%3F_u.date00=20190703%2526_u.date01=20190906%2526explorer- 
table.plotKeys=%5B%5D%2526explorer-table.rowStart=0%2526explorer- 
table.rowCount=1000&_r.userListReportId=app-visitors-user-id'
driver.get(url)
driver.find_element_by_name('identifier').send_keys('ID')
idlogin = driver.find_element_by_xpath('//*[@id="identifierNext"]/span/span')
idlogin.click()

driver.find_element_by_name('password').send_keys('PASSWD')
element = driver.find_element_by_id('passwordNext')
driver.execute_script("arguments[0].click();", element)
#login
driver.find_element_by_xpath("//*[@class='download-link']").click()
#click the download button

错误:

Message: no such element: Unable to locate element

inspection of GA

你可以试试文字:

如果要点击'Export'-

//button[contains(text(),'Export')]

您的点击元素位于 iFrame 中(iFrame id="galaxyIframe" ...)。因此,您需要告诉驱动程序从 "main" 页面切换到所说的 iFrame。如果您在 #login 之后添加这行代码,它应该可以工作: driver.switch_to.frame(galaxyIframe)

(如果框架没有名称,您将使用:iframe = driver.find_element_by_xpath("xpath-to-frame") 然后 driver.switch_to.frame(iframe)

要返回默认框架,请使用: driver.switch_to.default_content()

抓取 GA 通常是一种痛苦。不仅仅是因为这些 iFrame 无处不在。 除此之外,我建议研究 puppeteer,爬虫块上的新手。尽管从 python 切换到 javascript 的前景可能令人望而生畏,但这是值得的!一旦你进入它,selenium 就会感觉超级笨重。