我正在尝试选择此网站中未选中的复选框:https : //dataunodc.un.org/GSH_app,在“国家数据”中。此外,我想从下拉菜单(“显示...条目”)中选择“100”。
我正在使用硒和蟒蛇。你能告诉我怎么做吗?
这是与复选框选择对应的 HTML 代码的一部分:
<label class="checkbox-inline">
<input type="checkbox" name="YearVar" value="1990" checked="checked">
<span>1990</span>
</label>
<label class="checkbox-inline">
<input type="checkbox" name="YearVar" value="1991">
<span>1991</span>
</label>
<label class="checkbox-inline">
<input type="checkbox" name="YearVar" value="1992"
而这个对应下拉菜单:
name="DataTables_Table_0_length" aria-
controls="DataTables_Table_0" class=""><option
value="10">10</option><option
value="25">25</option><option
value="50">50</option><option
value="100">100</option></select> entries</label>
要获取所有未选中的复选框,然后单击这些复选框。
Induce WebDriverWait
() 和visibility_of_all_elements_located
() 以及以下XPATH
选项。然后迭代元素并单击每个元素。
#Get all checkbox which are not selected.
allchekbox=WebDriverWait(driver,10).until(EC.visibility_of_all_elements_located((By.XPATH,"//input[@name='YearVar' and not(@checked='checked')]")))
for item in allchekbox:
item.click()
为了选择
dropdown
使用 selenium 的值,请选择class
。
InduceWebDriverWait()
和visibility_of_element_located
() 和任一Xpath
选项。
XPATH 1:
# Select Item from dropdown
element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//select[starts-with(@name,'DataTables_Table_')]")))
select = Select(element)
select.select_by_value("100")
要么
XPATH 2:
element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//label[normalize-space(text())='Show']/select")))
select = Select(element)
select.select_by_value("100")
这是完整的代码:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
import time
driver = webdriver.Chrome()
driver.get("https://dataunodc.un.org/GSH_app")
driver.maximize_window()
#Switch the iframe in order to access the link
WebDriverWait(driver,15).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@src='https://unodc.shinyapps.io/GSH_App/']")))
#Click on National Data link
WebDriverWait(driver,5).until(EC.element_to_be_clickable((By.XPATH,'//ul[@class="nav navbar-nav"]//a[text()="National Data"]'))).click()
#Get all checkbox which are not selected.
allchekbox=WebDriverWait(driver,10).until(EC.visibility_of_all_elements_located((By.XPATH,"//input[@name='YearVar' and not(@checked='checked')]")))
#iterate and click each checkbox
for item in allchekbox:
item.click()
#To avoid StaleElementReferenceException add time.sleep()
time.sleep(2)
# Select Item from dropdown
element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//select[starts-with(@name,'DataTables_Table_')]")))
select = Select(element)
select.select_by_value("100")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句