我试图使用Selenium和Python 3从网站下载文件。这需要在覆盖窗口上按下确认按钮。叠加窗口不在iFrame中 - 当叠加层出现时,HTML只是动态添加 - 但Selenium无法通过xPath找到按钮,返回NoSuchElementException
。我错过了任何会导致Selenium无法看到页面源中出现的元素的内容吗?据我所知,Selenium应该能够找到没有问题的按钮。
#Initialize Driver
driver = webdriver.Safari()
cmd = "osascript -e 'tell application \"Safari\" to set bounds of front window to {0, 22, 1500, 1022}'"
os.system(cmd)
#Call up seach link
driver.get(data_url)
wait_a = WebDriverWait(driver, 15)
element = wait_a.until(EC.presence_of_element_located((By.ID, "md-input-3")))
#Initialize and send login information (defined above)
username = driver.find_element_by_id("md-input-3")
password = driver.find_element_by_id("md-input-6")
username.send_keys(crunchbase_username)
password.send_keys(crunchbase_password)
#Click login button
password.send_keys(Keys.ENTER)
#Wait for results page to finish loading
wait = WebDriverWait(driver, 15)
element = wait.until(EC.title_contains("Signals"))
time.sleep(2)
#Press Download Button
driver.find_element_by_xpath("//button[@aria-label='Export your results']").click()
time.sleep(2)
#Press csv button
driver.find_element_by_xpath("//button[@aria-label='Export to CSV']").click()
time.sleep(2)
#Confirm downlaod
driver.find_element_by_xpath("//*[@id='cdk-overlay-36']/md-dialog-container/confirmation-dialog/dialog-layout/div/md-dialog-actions/div/button[2]").click()
#Close driver
#driver.close()
页面源代码过于复杂和高度风格化,因此我不会在此处包含它,但是我的浏览器Web检查器中代码的相关部分的屏幕截图如下所示。我想点击的元素以蓝色突出显示。
我很感激任何帮助。
没有访问所讨论的页面并且能够看到发生了什么,很难说清楚。一般要点:
例如:
elemItems = driver.find_elements_by_css_selector(menuItemSelector)
for element in elements:
if element.text == "export":
elemItems[1].click()
在这里,您可以找到特定类型的所有元素(例如按钮),并选择其中包含“导出”文本的元素。
在单击元素之前,请执行以下行:
WebElement element = driver.findElement(By.xpath(" path_of_your_module "));
((JavaScriptExecutor) driver). executeScript("argument[0].scrollIntoView(true);", element);