selenium web中的下拉选项操作



from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium .webdriver.support.select import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException,NoSuchElementException
driver = webdriver.Chrome()
driver.get("https://baidu.com")
wait=WebDriverWait(driver,10) #显示等待
try:
# 鼠标移动到设置按钮
setting_element=wait.until(EC.presence_of_element_located((
By.LINK_TEXT,"设置"
)))
action_chains=ActionChains(driver)
action_chains.move_to_element(setting_element).perform()
# 点击高级设置
wait.until(EC.presence_of_element_located((
By.XPATH, "//div[@class='bdpfmenu']//a[contains(text(),'高级搜索')]"
))).click()


# 方法一:定位到下拉框,再点击选项

wait.until(EC.presence_of_element_located((By.XPATH, "//select[@name='gpc']/option[4]"))).click()


# 方法二 使用Select模块
format_selector=Select(wait.until(EC.presence_of_element_located((
By.XPATH,"//select[@name='ft']"
))))

# format_selector.select_by_value("all")
# format_selector.select_by_visible_text("所有格式")
format_selector.select_by_index(6) #从0开始计算的

wait.until(EC.presence_of_element_located((
By.XPATH,"//input[@id='adv_keyword']"
))).send_keys("柠檬班")

wait.until(EC.presence_of_element_located((
By.XPATH,"//input[@class='advanced-search-btn']"
))).click()

# 获取当前窗口数
windows=driver.window_handles
# 切换到最新的窗口
driver.switch_to.window(windows[-1])
file_name="lefix"+".png"
driver.get_screenshot_as_file(file_name)
except (TimeoutException,NoSuchElementException) as e:
print("出现异常{}".format(e))

finally:
driver.quit()




上一篇:添加K-CORE值进入运算


下一篇:SQL——视图