硒(Python)-选择 [英] Selenium (Python) - SELECT
问题描述
现在,在收到错误消息之前,我的脚本转到页面并打开下拉列表"Vijesti"中的第二个对象.
Right now my script go to page and open the second object from the drop down list, "Vijesti", before I get the error message.
这是错误:
StaleElementReferenceException:消息:在缓存中找不到元素-自查找以来,页面可能已更改
StaleElementReferenceException: Message: Element not found in the cache - perhaps the page has changed since it was looked up
在Selenium网站上:
From Selenium site:
当对元素的引用现在陈旧"时抛出. 陈旧意味着元素不再出现在页面的DOM上. StaleElementReferenceException的可能原因包括但不限于:
Thrown when a reference to an element is now "stale". Stale means the element no longer appears on the DOM of the page. Possible causes of StaleElementReferenceException include, but not limited to:
- 您不再位于同一页面上,或者自找到元素以来该页面可能已刷新.
- 该元素可能已被删除,并已重新添加到屏幕上.例如正在重定位的元素.当值更新并重建节点时,通常会在JavaScript框架中发生这种情况.
- 元素可能位于iframe或其他刷新的上下文中.
- You are no longer on the same page, or the page may have refreshed since the element was located.
- The element may have been removed and re-added to the screen, since it was located. Such as an element being relocated. This can happen typically with a javascript framework when values are updated and the node is rebuilt.
- Element may have been inside an iframe or another context which was refreshed.
我要选择每个对象并打开它.
What I want to select each object, and open it.
这是网址中的SELECT部分:
This is the SELECT part from the url:
<select id="kategorija" name="kategorija">
<option value="0">Kategorija</option>
<option value="12">Vijesti</option>
<option value="8">Biznis</option>
<option value="5">Sport</option>
<option value="2">Magazin</option>
<option value="7">Lifestyle</option>
<option value="3">Scitech</option>
<option value="6">Auto</option>
</select>
代码:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import time
driver = webdriver.Firefox()
driver.get("http://www.klix.ba/")
assert "Klix" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("test")
elem.send_keys(Keys.RETURN)
select = Select(driver.find_element_by_name('kategorija'))
all_options = [o.get_attribute('value') for o in select.options]
for x in all_options:
select.select_by_value(x)
time.sleep(3)
这是我进行测试的 url .
推荐答案
从下拉列表中选择一项后,页面会自动刷新.
您需要在每个选择的选项上重新查找" select
元素:
You need to "refind" the select
element on each option select:
select = Select(driver.find_element_by_name('kategorija'))
for index in range(len(select.options)):
select = Select(driver.find_element_by_name('kategorija'))
select.select_by_index(index)
# grab the results
这篇关于硒(Python)-选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!