因此,我一直试图在Python中使用Selenium来选择下拉菜单中的一些值,作为列表的筛选器。下面是我编写的代码和相关的xml。
…
<div id=“example_wrapper” class=“dataTables_wrapper”>
<div id=“example_filler” class=“dataTables_filter”>…</div>
<div class=“column-filter-wdigets”>
<div class=“column-filter-widget col-lg-2”>
<select class=“form-control input-sm widget-2”>
<option value>Level</option>
<option value=“1”>1</option>
<option value=“2”>2</option>
<option value=“3”>3</option>
<option value=“4”>4</option>
<option value=“5”>5</option>
<option value=“6”>6</option>
<option value=“7”>7</option>
<option value=“8”>8</option>
<option value=“9”>9</option>
</select>
....import requests, bs4, time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
print("\n\n")
browser = webdriver.Firefox()
browser.get('https://www.dnd-spells.com/spells')
selector = "div.column-filter-widget.col-lg-2"
try:
time.sleep(5)
levelList = browser.find_element_by_css_selector(selector)
print(type(levelList))
levelList.click()
levelListSelector = Select(levelList)
levelListSelector.select_by_value('3')
except:
print("First: No matches :/ \n\n")
try:
selector = "div > select"
levelOptions = browser.find_element_by_css_selector(selector)
print(levelOptions.text())
except:
print("Second: No matches :/ \n\n")问题是,虽然第一个选择器工作正常,但我看到下拉菜单列表打开,第二个选项不返回匹配项。我已经尝试了尽可能多的不同组合来获取选择标记,从非常具体到非常通用,但是没有任何效果。总是说没有找到火柴。
到了绳子的尽头,我决定看看我是否能得到那个选择标签,如果我把它作为我做的第一个选择的话。因此,我将顶部的选择器=“div.Colum-filter-widget.col-lg-2”更改为选择器=“div.Colum-filter-widget.col-lg-2 select”,并注释掉了第二个try/ out块。果然起作用了。但我不知道为什么。
有人能解释一下为什么会这样吗?我们不能从同一个web驱动程序甚至子元素中访问同一元素两次吗?我已经到了可以继续做我想做的事情的时候了,但是我想在这里理解这个问题,这样我就可以学习并在将来更好地处理它,如果需要的话。谢谢。
发布于 2019-12-11 16:47:00
文本是property,而不是function,这就是为什么您要获得exceptions。尝尝这个
try:
selector = "div > select"
levelOptions = browser.find_element_by_css_selector(selector)
print(levelOptions.text)
except:
print("Second: No matches :/ \n\n")发布于 2019-12-11 16:34:07
只有当您直接引用选择类型的元素(在html中)时,它才能工作。在您的示例中,您提供了一个指向div的元素。
请参阅python绑定文档(特别是在init上):https://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.support.select
https://stackoverflow.com/questions/59290009
复制相似问题