# 隨手小記
場景:測試百度:
點擊新聞,跳轉到新的窗口,找到輸入框,輸入“hello,world"
等到輸入框的內容是hello,world, 這里有個錯誤,少了一個]
后來就實現了錯誤截圖的功能,可以參考
//input[@id='ww'"
WebDriverWait(chrome_driver,10).until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,"//input[@id='ww'"),"hello,world"))
完整代碼?
# 通過xpath定位,By.XPATH
# xpath是一門在xml文檔中查找信息的語言
# 為什么使用xpath可以定位htmk
# html文檔的結構和標簽嵌套遵循XML的基本規則,因此XPath可以有效的用于html文檔中定位元素。XPath
# 從而實現定位
# xpath定位html的基本原則是,將html文檔視為xml文檔,并且使用Xpath表達式來描述元素的位置關系
# 選擇特定的元素或者元素集合# xpath可以通過相對路徑和絕對路徑去定位元素,絕對路徑從html根節點開始算,相對路徑從任意節點開始
import time
import osfrom selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditionschrome_driver = webdriver.Chrome()
try:# 1.從根節點開始選取:絕對路徑chrome_driver.get("https://www.baidu.com")chrome_driver.maximize_window()# 類變量 絕對路徑# chrome_driver.find_element(By.XPATH,)chrome_driver.implicitly_wait(10)chrome_driver.find_element(By.XPATH,'/html[1]/body[1]/div[1]/div[1]/div[3]/a[1]').click()# 切換窗口all_window = chrome_driver.window_handleschrome_driver.switch_to.window(all_window[1])# driver.findElement(By.xpath("//img[@alt='百度新聞']"))WebDriverWait(chrome_driver,10).until(expected_conditions.presence_of_element_located((By.XPATH,"//img[@alt='百度新聞']")))assert 'news' in chrome_driver.current_urlprint(chrome_driver.current_url)time.sleep(5)# 從任意節點開始取,//div 列出所有的div標簽web_eles = chrome_driver.find_elements(By.XPATH,'//div')print(web_eles)print(len(web_eles))# 這個網站取練手杠杠滴# https://iviewui.com/view-ui-plus/component/form/form#選取當前父節點是input的下面的a元素web_a = chrome_driver.find_elements(By.XPATH,'//div/a')print(len(web_a))# 根據屬性選取# 1.使用id屬性定位chrome_driver.find_element(By.XPATH,"//input[@id='ww']").send_keys("hello,world")WebDriverWait(chrome_driver,10).until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,"//input[@id='ww']"),"hello,world"))chrome_driver.find_element(By.XPATH,"//input[@id='ww']").clear()time.sleep(5)except Exception as e:# 截圖存儲的文件夾screenshot_dir = os.path.join(os.getcwd(), "screenshot")# 如果目錄不存在,則創建if not os.path.exists(screenshot_dir):os.makedirs(screenshot_dir)# 獲取當前截圖目錄下所有的 PNG 文件existing_screenshots = [f for f in os.listdir(screenshot_dir) if f.endswith(".png")]# 計算新的截圖編號new_index = len(existing_screenshots) + 1 # 從1開始累加# 生成新的截圖路徑screenshot_path = os.path.join(screenshot_dir, f"{new_index}.png")# 發生異常時截圖chrome_driver.save_screenshot(screenshot_path)print(f"操作失敗,已截圖: {screenshot_path}")print(f"錯誤信息: {e}")finally:# 關閉瀏覽器chrome_driver.quit()
最后的截圖
?