简体   繁体   English

如何使用css_selector选择硒python?

[英]How to select with css_selector selenium python?

I have the right code just its taking very long time until its selecting a random month. 我有正确的代码,只是花了很长时间才选择一个随机的月份。 It goes all options through to find that option. 它会遍历所有选项以找到该选项。 Any way to make it faster? 有什么方法可以使其更快?

Tried: 尝试过:

randomMonth = random.choice(["Jan","Feb","Mär","Apr","Mai","Jul","Aug","Sep","Okt","Nov","Dez"])
for i in driver.find_elements_by_tag_name("option"):
    if i.text == randomMonth:
        i.click()

Login Page from Payoneer.com Datepicker Month selection 来自Payoneer.com的登录页面日期选择器月份选择

<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">
    <option value="0" selected="selected">Jan</option>
    <option value="1">Feb</option>
    <option value="2">Mar</option>
    <option value="3">Apr</option>
    <option value="4">May</option>
    <option value="5">Jun</option>
    <option value="6">Jul</option>
    <option value="7">Aug</option>
    <option value="8">Sep</option>
    <option value="9">Oct</option>
    <option value="10">Nov</option>
    <option value="11">Dec</option>
</select>

You were close. 你近了 There is a helper class to make dealing with SELECT elements easier. 有一个帮助程序类,使处理SELECT元素更加容易。 You can use the Select class and choose the exact one you want without looping. 您可以使用Select类并选择您想要的确切类而无需循环。

from selenium.webdriver.support.ui import Select
...
randomMonth = random.choice(["Jan","Feb","Mär","Apr","Mai","Jul","Aug","Sep","Okt","Nov","Dez"])
select = Select(driver.find_element_by_css_selector("select.ui-datepicker-month"))
select.select_by_visible_text(randomMonth)

NOTE: You may have to adjust the CSS selector I chose if you have a lot of SELECT elements on the page but the basics on picking a random month and then selecting that from a dropdown should get you pointed in the right direction. 注意:如果页面上有很多SELECT元素,则可能必须调整我选择的CSS选择器,但是选择随机月份然后从下拉列表中进行选择的基础应该可以使您指向正确的方向。

See the python docs for more information about the Select class. 有关Select类的更多信息,请参见python文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM