我编写了一个脚本,使用python和selenium从网页中选择某个字段。该页面上有一个下拉列表,我想从中选择“全部”。但是,我尝试了许多不同的方法来制作它但不能。 下面是下拉列表的样子。
下拉列表选择的Html元素:
<select name="ctl00$body$MedicineSummaryControl$cmbPageSelection" onchange="javascript:setTimeout('__doPostBack(\'ctl00$body$MedicineSummaryControl$cmbPageSelection\',\'\')', 0)" id="ctl00_body_MedicineSummaryControl_cmbPageSelection">
<option selected="selected" value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="all">All</option>
</select>
我试过的脚本:
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://apps.tga.gov.au/Prod/devices/daen-entry.aspx')
driver.find_element_by_id('disclaimer-accept').click()
time.sleep(5)
driver.find_element_by_id('medicine-name').send_keys('pump')
time.sleep(8)
driver.find_element_by_id('medicines-header-text').click()
driver.find_element_by_id('submit-button').click()
time.sleep(7)
#selection for the dropdown should start from here
driver.find_element_by_xpath('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').click()
driver.find_element_by_xpath('//select//option[@value]').send_keys("All")
答案 0 :(得分:2)
这对你有用:
#option1
select_obj = Select(driver.find_element_by_xpath('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]'))
select_obj.select_by_visible_text('All')
#option2
select_obj = Select(driver.find_element_by_id('ctl00_body_MedicineSummaryControl_cmbPageSelection'))
select_obj.select_by_visible_text('All')
不要忘记使用Select
from selenium.webdriver.support.ui import Select
您可以在此处阅读完整文档以查找所有Select
方法:https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.select.html
答案 1 :(得分:0)
我最初想过建议您尝试从下拉选择之前的元素中进行制表,类似于此代码中的概念:
driver.find_element_by_id('<id of element before the dropdown select>').send_keys(Keys.TAB)
driver.find_element_by_id('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').send_keys('AL')
driver.find_element_by_id('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').send_keys(Keys.ENTER + Keys.TAB)
但是,堆栈跟踪中的错误可能会显示找不到该ID的下拉列表选项。我相信,当您通过使用Selenium IDE中的Record选项记录单击下拉选择并选择选项的操作时,您应该验证您正在使用的id是该元素的正确ID。
答案 2 :(得分:0)
最终找到了解决方法。这是我做的:
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://apps.tga.gov.au/Prod/devices/daen-entry.aspx')
driver.find_element_by_id('disclaimer-accept').click()
time.sleep(5)
driver.find_element_by_id('medicine-name').send_keys('pump')
time.sleep(8)
driver.find_element_by_id('medicines-header-text').click()
driver.find_element_by_id('submit-button').click()
time.sleep(7)
driver.find_element_by_xpath('//select[@id="ctl00_body_MedicineSummaryControl_cmbPageSelection"]').click()
driver.find_element_by_xpath('.//option[@value="all"]').click()
time.sleep(10)