Python Selenium:找不到Xpath元素

时间:2016-03-30 22:29:54

标签: python selenium xpath

我试图点击网页的某个部分,但我收到了消息" NoSuchElementException:无法找到元素" ....尽管元素在那里。

用于工作的代码,但看起来页面有变化..但xpath没有改变。

我在Stackoverflow中尝试了类似问题的不同解决方案,但是对于这个例子来说还不正确。

网址是: " http://www.bmfbovespa.com.br/pt_br/servicos/market-data/consultas/mercado-a-vista/codigo-isin/pesquisa/"

我试图点击的元素:"下载de Arquivos"

我的代码:

from selenium import webdriver 


fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/msword, application/csv, application/vnd.ms-excel, application/ris, text/csv, image/png, application/pdf, text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, application/octet-stream")
fp.set_preference('browser.helperApps.alwaysAsk.force', False) 



driver = webdriver.Firefox(firefox_profile=fp)
driver.get("http://www.bmfbovespa.com.br/pt_br/servicos/market-data/consultas/mercado-a-vista/codigo-isin/pesquisa/")

###
# Click "Download de arquivos" (the part with problem)
###

elem=driver.find_element_by_xpath(".//*[@id='ctl00_contentPlaceHolderConteudo_rtsDetalhe_tabDownload']/span/span")
elem.click()

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

此处有多个选项:

  • 找到“by id”链接:

    driver.find_element_by_id("ctl00_contentPlaceHolderConteudo_rtsDetalhe_tabDownload")
    
  • 通过链接文本通过“by xpath”定位器:

    driver.find_element_by_xpath("//a[span/span = 'Download de Arquivos']")
    

而且,重要的是元素在iframe内 - 你需要切换到它。

工作代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://www.bmfbovespa.com.br/pt_br/servicos/market-data/consultas/mercado-a-vista/codigo-isin/pesquisa/")

driver.switch_to.frame("bvmf_iframe")

wait = WebDriverWait(driver, 10)
elem = wait.until(EC.presence_of_element_located((By.ID, "ctl00_contentPlaceHolderConteudo_rtsDetalhe_tabDownload")))
elem.click()