我想使用爬虫下载 Google Analytics 上的用户数据,因此我使用 selenium 编写了一些代码。但是,我无法单击“导出”按钮。它总是显示错误“没有这样的元素”。我尝试使用 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
最佳答案
您的点击元素位于 iFrame 中(iFrame id="galaxyIframe"...)。因此,您需要告诉驱动程序从“主”页面切换到所述 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 ,履带 block 上的新 child 。尽管从 python 切换到 javascript 的前景可能令人畏惧,但这是值得的!一旦你深入其中,你就会觉得 Selenium 非常笨重。
关于python - 我怎样才能在Python中的selenium上下载 "click"按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57933915/