【问题标题】:Selenium (Python) - SELECT硒(Python)-选择
【发布时间】:2015-11-29 16:32:04
【问题描述】:

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

这是错误:

StaleElementReferenceException: Message: Element not found in the cache - 也许页面在查找后发生了变化

来自 Selenium 网站:

当对元素的引用现在“过时”时抛出。 陈旧意味着元素不再出现在页面的 DOM 上。 StaleElementReferenceException 的可能原因包括但不限于:

  • 您不再在同一个页面上,或者在找到元素后页面可能已刷新。
  • 该元素可能已被删除并重新添加到屏幕,因为它已被定位。比如一个元素被重新定位。当更新值并重建节点时,这通常会发生在 javascript 框架中。
  • 元素可能位于 iframe 或其他已刷新的上下文中。

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

这是来自 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

【问题讨论】:

    标签: python selenium selenium-webdriver


    【解决方案1】:

    当从下拉列表中选择项目时,页面会自行刷新

    您需要在每个选项选择上“重新查找”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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多