簡體   English   中英

使用 Selenium 和 Python 單擊下拉列表中的元素

[英]Click on element in dropdown with Selenium and Python

在 MacOS 上使用 Selenium 和 Chrome webdriver 需要單擊下拉元素。 但是總是有找不到的錯誤。 在它所在的頁面上有這個 html 代碼:

<select id="periodoExtrato" name="periodoExtrato" class="EXTtexto" onchange="enviarExtrato(document.formperiodo.periodoExtrato[document.formperiodo.periodoExtrato.selectedIndex].value);">
<!--<option value="01" >&Uacute;ltimo dia</option>-->
<option value="03" selected="true">Últimos 3 dias</option>
<option value="05">Últimos 5 dias</option>
<option value="07">Últimos 7 dias</option>
<option value="15">Últimos 15 dias</option>
<option value="30">Últimos 30 dias</option>
<option value="X">Data específica (até 60 dias)</option>
<option value="D">Mês completo (desde 2002)</option>
</select>

我需要選擇Últimos 15 dias,所以我有這個代碼:

self.driver.find_element_by_xpath('//[@id="periodoExtrato"]/option[4]').click()

但是有一個錯誤:

Traceback (most recent call last):
  File "olxscrape.py", line 120, in <module>
    main()
  File "olxscrape.py", line 117, in main
    b = Bot()
  File "olxscrape.py", line 12, in __init__
    self.navigate()
  File "olxscrape.py", line 106, in navigate
    self.driver.find_element_by_xpath('//*[@id="periodoExtrato"]/option[4]').click()
  File "/Users/Lutchenko/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 293, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "/Users/Lutchenko/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 752, in find_element
    'value': value})['value']
  File "/Users/Lutchenko/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "/Users/Lutchenko/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="periodoExtrato"]/option[4]"}
  (Session info: chrome=55.0.2883.95)
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Mac OS X 10.12.2 x86_64)

我建議不要在這里使用 xpath。 相反,嘗試這樣的事情:

 select = Select(self.driver.find_element_by_id('periodoExtrato'))
 option_indexes = range(1, len(select.options))
 for index in option_indexes:
    select.select_by_index(index)
    ......

一個問題是<frameset>中的元素在</head>之后,所以 selenium 找不到它。 添加這個字符串后問題解決了。

browser.switch_to_frame('name')

在那之后

self.driver.find_element_by_xpath('//[@id="periodoExtrato"]/option[4]').click()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM