我是在Python中使用Selenium的新手,并且正在尝试访问Barclays Live网站上的索引数据。登录并加载页面后,我试图从页面的下拉菜单中选择“ Custom1”。与列表关联的HTML代码中的select对象如下所示:
<select name="customViewId" class="formtext" onchange="submitFromSelect('username');return false;">
<option value=""> </option>
<option value="Favorite Indices">Favorite Indices</option>
<option value="Custom1">Custom1</option>
<option value="CB group">CB group</option>
<option value="Kevin Favorites">Kevin Favorites</option>
<option value="LB Gov/Cdt intermediate">LB Gov/Cdt intermediate</option>
</select>
这是我的代码,直到我尝试访问该对象为止:
from selenium import webdriver
from selenium.webdriver.support.select import Select
#Get chrome driver and connect to Barclays live site
browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\chromedriver.exe")
browser.get('https://live.barcap.com/')
#Locate username box and enter username
username = browser.find_element_by_name("user")
username.send_keys("username")
#Locate password box and send password
password = browser.find_element_by_name("password")
password.send_keys("password")
#Click login button
login = browser.find_element_by_id("submit")
login.click()
#Open page where you can select indices
browser.get("https://live.barcap.com/BC/barcaplive?menuCode=MENU_IDX_1061")
我已经尝试了许多建议的解决方案,通常会出现错误“无法找到元素:”,然后是尝试访问选择对象的任何方法。我似乎无法通过名称,xpath或使用Select()函数来访问它。我尝试将等待时间放入代码中,以防元素尚未加载,也没有运气。我希望它们能起作用的一些示例,但并非如此:
select_box = browser.find_element_by_name("customViewId")
select_box = browser.find_element_by_xpath("//select[option[@value='Custom1']]"
我的背景不是编程,如果这是一个愚蠢的问题,请放轻松。在此先感谢您的帮助。
select元素确实位于iframe中。
这意味着您应该切换到框架的上下文,然后才能找到该元素:
browser.switch_to.frame("frame_name_or_id")
select_box = browser.find_element_by_name("customViewId")
如果您需要从框架的上下文中找回,请使用:
browser.switch_to.default_content()
至于操纵选择框部分,还有一种更好的方法-使用Select
class:
from selenium.webdriver.support.select import Select
select_box = Select(browser.find_element_by_name("customViewId"))
select_box.select_by_visible_text("CB group")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句