我无法获得元素

时间:2019-08-22 02:45:09

标签: python selenium-webdriver

我只得到第一条文字(--chose--)

为什么不打印所有结果(good_1, good_2,...) 请在这里怎么了


drop_down = driver.find_elements_by_css_selector(".select2-container--default")[4]
ActionChains(driver).move_to_element(drop_down).perform()
drop_down.click()
time.sleep(1)
drop_down = driver.switch_to.active_element
element = driver.find_elements_by_css_selector(".select2-container--default")[4]
print(element.text)
all_options = drop_down.find_elements_by_tag_name("option")
for option in element:
    print(option.text)


此代码与问题相同:

element = driver.find_element_by_css_selector("#select2-ctl00_PlaceHolderMain_ddlPeriod-container")

HTML:





<div class="col-xs-12 no_padding" printable="true">
<div class="col-xs-5 col-sm-4 feild_title">
<span id="ctl00_PlaceHolderMain_tdPeriod" class="manditory">*</span>
<span id="ctl00_PlaceHolderMain_lblPeriodTitle" class="StandardFont" style="display:inline-block;width:100px;">test</span>
</div>
<div class="col-xs-7 col-sm-8 feild_data">
<select name="ctl00$PlaceHolderMain$ddlPeriod" onchange="javascript:setTimeout(&#39;__doPostBack(\&#39;ctl00$PlaceHolderMain$ddlPeriod\&#39;,\&#39;\&#39;)&#39;, 0)" id="ctl00_PlaceHolderMain_ddlPeriod" class="control-dropdownlist" style="width:100%;">
<option selected="selected" value="-99">-- chose --</option>
<option value="200140">good_1</option>
<option value="200141">good_2</option>
<option value="200142">good_3</option>
<option value="200143">good_4</option>
</select>
<span id="ctl00_PlaceHolderMain_rfvPeriod" class="ValidationClass" style="display:inline-block;width:150px;display:none;">chose one.</span>
</div>
</div>


错误:

  

-选择-

     

进程以退出代码-1073740791(0xC0000409)完成

2 个答案:

答案 0 :(得分:1)

尝试像下面这样使用xpath

opts = driver.find_elements_by_xpath('//option[text() and ./parent::*[@id="ctl00_PlaceHolderMain_ddlPeriod"]]')
for opt in opts:
    print(opt.text)

答案 1 :(得分:0)

您的代码中有错字:

更改此:

for option in element:
    print(option.text)

对此:

for option in all_options:
    print(option.text)

还要了解到,使用time.sleep()是某种表现形式anti-pattern,请考虑改用Explicit Wait。请查看How to use Selenium to test web applications using AJAX technology文章,以获取全面的说明和示例。