from selenium import webdriver from selenium.webdriver.common.keys import Keys import time from selenium.webdriver import ActionChains # driver= webdriver.Firefox() driver= webdriver.Chrome() driver.get("https://www.baidu.com/") driver.maximize_window() driver.find_element_by_xpath("//*[@id=\"kw\"]").send_keys("selenium") driver.find_element_by_xpath("//*[@id=\"kw\"]").submit() #鼠标悬停+点击隐藏的按钮 #1.鼠标放上去 time.sleep(2) # above=driver.find_element_by_xpath("//span[@id=\"s-usersetting-top\"]") above=driver.find_elements_by_xpath("//*[text()=\"设置\"]")[1] ActionChains(driver).move_to_element(above).perform() SearchSetting_Ele=driver.find_element_by_xpath("//*[text()=\"搜索设置\"][1]") SearchSetting_Ele.click() #2.利用JS改变页面属性,例如输入日期没必要测试第三方控件,不是我们测试范围的话,就可以改变控件属性改成输入日期。不常用,实在是没有办法才用 # js2 = 'document.querySelectorAll("div#head #s-user-setting-menu")[0].style.display="block";' # driver.execute_script(js2) #3.利用JQery鼠标悬停方法 # js1 = "$('#s-usersetting-top').mouseover()" # jQuery 模拟鼠标悬停 # driver.execute_script(js1) time.sleep(2) # driver.find_elements_by_xpath("//*[text()='高级搜索']")[1].click() driver.find_element_by_xpath("(//*[text()='高级搜索'])[2]").click() driver.find_element_by_xpath("//*[@id=\"adv_keyword\"]").send_keys("包含全部关键词") driver.find_element_by_xpath("//input[@class=\"c-input adv-q-input switch-input\" and @name=\"q2\"]").send_keys("包含完整关键词") driver.find_element_by_xpath("//input[@class=\"c-input adv-q-input switch-input\" and @name=\"q3\"]").send_keys("包含任意关键词") driver.find_element_by_xpath("//div[@class=\"c-select-selection\"]/i[1]").click() driver.find_element_by_xpath("//p[@class=\"c-select-item\" and @data-for=\"gpc\"][4]").click() driver.find_element_by_xpath("(//i[@class=\"c-icon c-select-arrow\"])[2]").click() driver.find_element_by_xpath("//*[text()=\"所有格式\"]").click() driver.find_element_by_xpath("//*[@id=\"q5_2\"]").click() # driver.find_element_by_xpath("//*[@value=\"高级搜索\"]").click() # time.sleep(2) driver.find_element_by_xpath("//*[@class=\"item\" and @data-tabid=\"general\"]").click() driver.find_element_by_xpath("//*[text()=\"保存设置\"]").click()
第二种方法可能行不通,因为隐藏的按钮在页面加载后还没有被渲染,所有找不到该元素就无法修改其属性。