使用硒检查盒子的有效方法

时间:2018-06-11 19:52:25

标签: python python-3.x selenium selenium-webdriver web-scraping

我在python中编写了一个与selenium结合的脚本来解开两个连接到两个按钮的盒子。然后在这两个框中有几个字段来检查或取消选中选项。

使用下面的脚本,我可以检查所需的框连接到前两个按钮但事情是我做的方式整个操作是非常不整洁。我怎么能以有效的方式做到这一点?

我尝试过的脚本:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("http://urbantoronto.ca/database/")
wait = WebDriverWait(driver, 10)

wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#filter_status_arrow"))).click()
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#check_pre_construction"))).click()
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#check_complete"))).click()

wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#filter_project_type_arrow"))).click()
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#check_condo"))).click()
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#check_co_op"))).click()
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#check_house"))).click()

driver.quit()

默认情况下the buttons look like this

当我选择所需的字段时,他们look like this

我怎样才能以有效的方式做到这一点?

1 个答案:

答案 0 :(得分:1)

仍然不确定“高效方式”的含义。

尝试以下解决方案,如果需要进行一些改进,请告知我们:

driver.get("http://urbantoronto.ca/database/")

# Use @id of filter as key, @ids of check-box as values
filters = {"filter_status": ["pre_construction", "under_construction", "complete"],
           "filter_project_type": ["condo", "hotel", "institutional"]}

for filter_item in filters:
    driver.find_element_by_id("%s_arrow" % filter_item).click()
    for checkbox in filters[filter_item]:
        driver.find_element_by_id(filter_item).find_element_by_id("check_%s" % checkbox).click()