与不可见元素交互并访问第二个匹配元素

2024-09-27 17:49:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从下拉选项中选择一个值。html如下: (网站是http://www.flightstats.com/go/FlightStatus/flightStatusByAirport.do

<select id="airportQueryTime" name="airportQueryTime" onchange="selectTime(this); return true;" value="6">
 <option onchange="selectTime(this); return true;" selected="selected" value="6">
  6:00AM - 7:00AM
 </option>
 <option onchange="selectTime(this); return true;" value="7">
  7:00AM - 8:00AM
 </option>
 <option onchange="selectTime(this); return true;" value="8">
  8:00AM - 9:00AM
 </option>
 <option onchange="selectTime(this); return true;" value="9">
</select>



from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

url = 'http://www.flightstats.com/go/FlightStatus/flightStatusByAirport.do;jsessionid=7B477D6D5CFB639F96C5D855CEB941D0.web4:8009?airport=LAX&airportQueryDate=2014-09-06&airportQueryTime=-1&airlineToFilter=&airportQueryType=0&x=0&y=0'
driver = webdriver.Firefox()
driver.get(url)
time.sleep(6)
element = driver.find_element_by_xpath("//select[@id='airportQueryTime']/option[@value='0']")
element.click()

我的问题是:

  1. 因为如果我通过ID找到element by ID='airportQueryTime'有三个标记,我需要的元素是第二个。如何访问第二个匹配元素?

  2. 我试图使用下面的代码选择value=0选项,但是selenium引发了一个错误。在

    在selenium.common.异常.ElementNotVisibleException:消息:u'Element当前不可见,因此可能无法与“


Tags: importtruereturnvalue选项driverseleniumelement
1条回答
网友
1楼 · 发布于 2024-09-27 17:49:47

selenium有一个特殊的^{}类,用于与selectoption标记交互:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select


url = 'http://www.flightstats.com/go/FlightStatus/flightStatusByAirport.do;jsessionid=7B477D6D5CFB639F96C5D855CEB941D0.web4:8009?airport=LAX&airportQueryDate=2014-09-06&airportQueryTime=-1&airlineToFilter=&airportQueryType=0&x=0&y=0'
driver = webdriver.Firefox()
driver.get(url)

select = Select(driver.find_element_by_xpath("//div[@class='uiComponent674']//select[@id='airportQueryTime']"))

# print all the options
print [element.text for element in select.options]

# select option by text
select.select_by_visible_text('6:00AM - 7:00AM')

注意,由于页面上有多个具有airportQueryTimeid的元素,我们必须在div范围内使用uiComponent674类(用于选择时间间隔的块)搜索它。在

相关问题 更多 >

    热门问题