在處理懸浮後出現的下拉框時,碰到過下面兩種報錯
在百度首頁,將鼠標懸浮到"設置",然後移動到"高級搜索"並點擊
報錯代碼:
# 等待"設置"按鈕出現
WebDriverWait(dr,30).until(EC.visibility_of_element_located((By.XPATH,"//span[text()='設置']")))
# 用ActionChains鏈的形式,將鼠標移動到"設置",然後點擊"高級搜索"
ac = ActionChains(dr)
ac.move_to_element(dr.find_element_by_xpath("//span[text()='設置']")).\
click(dr.find_element_by_xpath("//div[@class='s-user-setting-pfmenu']/a[text()='高級搜索']")).perform()
# click()中的dr報錯
time.sleep(5)
dr.quit()
執行結果
我先按照ActionChains的分步式修改,修改後還是不行
最後依次perform move_to_element/click,執行成功
修改後的代碼
dr = webdriver.Edge()
dr.get("http://www.baidu.com")
dr.maximize_window()
WebDriverWait(dr,30).until(EC.visibility_of_element_located((By.XPATH,"//span[text()='設置']")))
ac = ActionChains(dr)
ac.move_to_element(dr.find_element_by_xpath("//span[text()='設置']")).perform()
ac.click(dr.find_element_by_xpath("//div[@class='s-user-setting-pfmenu']/a[text()='高級搜索']")).perform()
time.sleep(5)
dr.quit()
在58同城-品牌公寓頁面(https://sjz.58.com/pinpaigongyu/),將鼠標懸浮到"位置"-“區域”-“長安”
# 在"品牌公寓"頁面,將目標房產滾動到可是區域
element_wz = driver.find_element_by_xpath('//div[@class="selectBar select-item"]//li[@class="wz"]')
action = ActionChains(driver)
action.move_to_element(element_wz).perform()
# WebDriverWait(driver, 15).until(EC.visibility_of_element_located((By.XPATH, '//div[@class="selectBar select-item"]//a[@listname="changan"]')))
element_1 = driver.find_element_by_xpath(
'//div[@class="selectBar select-item"]//div[@class="wz-mod1"]/a[@class="select"]')
action.move_to_element(element_1).perform()
# 下面這一行find報錯
action.move_to_element\
(driver.find_element_by_xpath('//div[@class="selectBar select-item"]//a[@listname="changan"]')).perform()
報錯:stale element reference: element is not attached to the page document(元素未加載到頁面)
element_wz = driver.find_element_by_xpath('//div[@class="selectBar select-item"]//li[@class="wz"]')
action = ActionChains(driver)
action.move_to_element(element_wz).perform()
element_1 = driver.find_element_by_xpath('//div[@class="selectBar select-item"]//div[@class="wz-mod1"]/a[@class="select"]')
action.move_to_element(element_1).perform()
# 1.將鼠標移動到"區域"後,頁面重新刷新了."長安"標簽就定位不到.
action_new = ActionChains(driver)
# 2.使用刷新後的driver 創建ActionChains實例,就可以繼續定位了
time.sleep(5)
element_2 = driver.find_element_by_xpath('//div[@class="selectBar select-item"]//a[@listname="changan"]')
action_new.move_to_element(element_2).perform()