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

selenium.common.exceptions.NoSuchElementException from dynamic content

有 a form on 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"}}

我该怎么办?

错误是因为您定位的字段在 iFrame 中。 因此,首先您需要切换到 iframe,然后定位您的元素。 仍然,如果不起作用,请添加时间延迟。

要定位 iFrame:

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

然后切换到 iFrame

driver.switchTo().frame(iframelocator);

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

: 以上代码在java中。