来自动态内容的selenium.common.exceptions.NoSuchElementException

时间:2017-01-25 23:24:54

标签: python selenium webdriver phantomjs element

a form上有this site,我正试图从中获取所有选项并点击带有此代码的搜索按钮:

from selenium import webdriver

driver = webdriver.PhantomJS('c:\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe')

driver.get('http://www.cobar.org/Find-A-Lawyer')
driver.implicitly_wait(20)
options = driver.find_element_by_xpath('//select[@id="FAL_FOP_field"]')
for option in options.find_elements_by_tag_name('option'):
    if option.text != 'ALL':
        option.click()
        #click search button
        driver.find_element_by_xpath('//button[@class="btn btn-primary btn-main"]').click()

        lawyer = driver.find_element_by_xpath('//table[@id="myTable"]/tbody/tr/td[0]')
        print(lawyer)

但是我得到了:

selenium.common.exceptions.NoSuchElementException: Message: {"errorMessage":
"Unable to find element with xpath '//select[@id=\"FAL_FOP_field\"]'",
"request":{"headers":{"Accept":"application/json","Accept-Encoding":
"identity","Connection":"close","Content-Length":"115","Content-Type":
"application/json;charset=UTF-8","Host":"127.0.0.1:52809","User-Agent":"Python-urllib/2.7"}
,"httpVersion":"1.1","method":"POST","post":
"{\"using\": \"xpath\", \"sessionId\": \"e03be070-e353-11e6-83b5-5f7f74696cce\","
" \"value\": \"//select[@id=\\\"FAL_FOP_field\\\"]\"}","url":"/element",
"urlParsed":{"anchor":"","query":"","file":"element","directory":"/",
"path":"/element","relative":"/element","port":"","host":"","password":"","user":"",
"userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},
"chunks":["element"]},"urlOriginal":"/session/e03be070-e353-11e6-83b5-5f7f74696cce/element"}}

我该怎么办?

1 个答案:

答案 0 :(得分:2)

错误是因为您要查找的字段位于 iFrame 内。 所以,首先你需要切换到iframe,然后找到你的元素。 如果不起作用,加上时间延迟。

找到iFrame:

WebElement iframelocator = driver.findElement(By.xpath("//iframe[@id='dnn_ctr2047_IFrame_htmIFrame']"));

然后切换到iFrame

driver.switchTo().frame(iframelocator);

在定位元素之前,在代码中添加以上两个步骤。

注意:以上编写的代码在java中。