问题:由于display: none属性隐藏了下拉选择,导致无法被select选中

方法一:直接点击的方式避开,这个方法最粗暴快捷,但是如果无法成功则选择方法二
python
# 选择省-北京市
driver.find_element(By.XPATH,'/html/body/div[1]/form/div[4]/div[1]/a/span').click()
driver.find_element(By.XPATH,'/html/body/div[1]/form/div[4]/div[1]/div/ul/li[2]').click()
# 选择城市-东城区
driver.find_element(By.XPATH,'/html/body/div[1]/form/div[4]/div[2]/a/span').click()
driver.find_element(By.XPATH,'/html/body/div[1]/form/div[4]/div[2]/div/ul/li[2]').click()
# 选择区县-东四街道
driver.find_element(By.XPATH,'/html/body/div[1]/form/div[4]/div[3]/a/span').click()
driver.find_element(By.XPATH,'/html/body/div[1]/form/div[4]/div[3]/div/ul/li[3]').click()
方法二:JS直接赋值,绕过前端交互
python
# 省份选择
province_select = driver.find_element(By.NAME, "province") #省
# 1. 赋值+触发带冒泡的change + 强制刷新Chosen显示
driver.execute_script("""
// 给原生select赋值
arguments[0].value = "3";
// 带冒泡的change事件(让前端监听到)
arguments[0].dispatchEvent(new Event('change', {bubbles: true}));
// 强制刷新Chosen组件,如果有没有Chosen组件则不需要这一步(如何判断:元素定位后查看元素属性,是否有chosen关键字出现)
$(arguments[0]).trigger('chosen:updated');
""", province_select)
# sleep(3) #等待数据加载
# 或用显式等待
from selenium.webdriver.support.wait import WebDriverWait
wait = WebDriverWait(driver, 10)
wait.until(lambda d: len(d.find_elements(By.XPATH, '//select[@name="city"]/option[@value="73"]')) > 0)
# 城市选择
city_select = driver.find_element(By.NAME, "city") #市
driver.execute_script("""
arguments[0].value = "73";
arguments[0].dispatchEvent(new Event('change', {bubbles: true}));
$(arguments[0]).trigger('chosen:updated');
""", city_select)
# sleep(3)
wait.until(lambda d: len(d.find_elements(By.XPATH, '//select[@name="county"]/option[@value="1126"]')) > 0)
# 区县选择
city_select = driver.find_element(By.NAME, "county") #市
driver.execute_script("""
arguments[0].value = "1126";
arguments[0].dispatchEvent(new Event('change', {bubbles: true}));
$(arguments[0]).trigger('chosen:updated');
""", city_select)