使用Selenium / Firefox无法找到/单击此按钮

时间:2016-06-08 16:11:57

标签: python selenium firefox xpath

我试图按下这个"新搜索"按钮。在http://www.lexisnexis.com/hottopics/lnacademic/

上输入搜索后,它会显示在屏幕顶部

我查看了Xpath和Unique Selector。

我尝试过:

browser.find_element_by_css_selector('#restoreButtons > a:nth-child(3)').click()
browser.find_element_by_xpath(id('restoreButtons')/x:a[3])
browser.find_element_by_xpath(/x:a[3])

对于这三个人,我得到一个"无法定位元素错误"

2 个答案:

答案 0 :(得分:0)

这是因为元素在iframe内是你必须在上下文中搜索里面的元素。使用.switch_to.frame()

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

wait = WebDriverWait(driver, 10)
frame = wait.until(EC.presence_of_element_located((By.ID, "mainFrame")))
driver.switch_to.frame(frame)

仅供参考,这是完整的工作代码:

from selenium import webdriver
from selenium.webdriver import ActionChains
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()
driver.get('http://www.lexisnexis.com/hottopics/lnacademic/')

actions = ActionChains(driver)
wait = WebDriverWait(driver, 10)

frame = wait.until(EC.presence_of_element_located((By.ID, "mainFrame")))
driver.switch_to.frame(frame)

driver.find_element_by_id("terms").send_keys("Test")
driver.find_element_by_id("srchButt").click()

答案 1 :(得分:0)

建立在alecxes的答案上,

一旦进入iframe,就可以使用它的xpath找到可点击的内容:

new_search_xpath = '/html/body/div[2]/table/tbody/tr[2]/td[2]/div[1]/table/tbody/tr/td/span/a[3]'
new_search = driver.find_element(By.XPATH, new_search_xpath)
new_search.click()

你应该考虑安装firebug firefox addon来抓取Xpath: https://addons.mozilla.org/en-US/firefox/addon/firebug/