python - Selenium (Python)-选择

标签 python selenium selenium-webdriver

现在,在我收到错误消息之前,我的脚本转到页面并从下拉列表“Vijesti”中打开第二个对象。

这是错误:

StaleElementReferenceException: Message: Element not found in the cache - perhaps the page has changed since it was looked up

来自 Selenium 网站:

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:

  • 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.

我要选择每个对象,并打开它。

这是 URL 中的 SELECT 部分:

<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 元素:

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 - Selenium (Python)-选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32382415/

相关文章:

python - 使用 selenium 登录网页

python - 如何使用 Selenium for Firefox (geckodriver) 将 navigator.webdriver 设置为未定义

python - 对 Django Q 对象执行逻辑异或

等高线图中的 Python Matplotlib 非线性缩放

python - X 阵列 : Loading several CSV files into a dataset

selenium - 是否可以使用 Selenium/Capybara 截取整个页面?

javascript - 未捕获错误 : process. 不支持绑定(bind)(browserify+selenium-webdriver)

java - Selenium WebDriver - 在测试期间删除 cookie 并重新启动浏览器

Phpunit - Selenium2 - 等待页面完全加载

3D 中的 Python 频谱图(类似于 matlab 的频谱图函数)