下面的代码适用于Firefox,但是当我设置browser = webdriver.Chrome()时,我遇到了一些问题。
browser = webdriver.Firefox()
browser.get('https://www.voilanorbert.com/')
inputElement = browser.find_element_by_id("form-search-name")
inputElement.send_keys(leadslist[i][0])
inputElement = browser.find_element_by_id("form-search-domain")
inputElement.send_keys(leadslist[i][1])
searchbutton = browser.find_element_by_name("search")
searchbutton.click()
wait = WebDriverWait(browser, 20)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.results")))
h3s = browser.find_elements_by_css_selector('h3.one')
h3 = next(element for element in h3s if element.is_displayed())
result = h3.text
使用chrome,一切都很好,直到我需要提取文本。我收到这个错误:
h3 = next(element for element in h3s if element.is_displayed())
StopIteration
修改
问题再次出现在firefox和chrome上。我甚至加了一个流利的等待。
wait = WebDriverWait(browser, 20)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.results")))
wait2 = WebDriverWait(browser, 3000, poll_frequency=100, ignored_exceptions=[ElementNotVisibleException])
wait2.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "h3.one")))
h3s = browser.find_elements_by_css_selector('h3.one')
h3 = next(element for element in h3s if element.is_displayed())
result = h3.text
我得出的结论是,硒绝对不是完美的。
答案 0 :(得分:1)
我怀疑这里的关键问题是在显示结果时发生的动画。
您需要让selenium
知道您希望在通过implicitly_wait()
搜索元素之前等待:
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.results")))
# okay, selenium, slow down, please
browser.implicitly_wait(3)
h3s = browser.find_elements_by_css_selector('h3.one')
(为我工作)
答案 1 :(得分:1)
如果是等待问题,我在流利的等待中有很好的经验:
https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html