Xpath的一些定位技巧
常用的命令可以參考以下
https://blog.csdn.net/u013332124/article/details/80621638
https://blog.csdn.net/baidu_32542573/article/details/79675420
藉助谷歌瀏覽器的Console進行定位的驗證
驗證css,命令: $$(""),雙引號內寫css表達式。
驗證xpath,命令:$x(""),雙引號內寫xpath表達式。例如
打開http://www.w3school.com.cn/xpath/xpath_axes.asp,檢驗以下表達式:
$x(’//[@id=“maincontent”]/div[3]/table/tbody/tr[6]/child::td[2]/preceding-sibling::td/parent::/ancestor::table/attribute::class’)
$x(’//[@id=“maincontent”]/div[3]/table/tbody/tr[6]/child::td[2]/preceding-sibling::td/parent::/ancestor::table/ancestor::div[2]’)
序號從1開始!
基本用法
表達式 | 描述 |
---|---|
nodename | 選取此節點的所有子節點。 |
/ | 從根節點選取。 |
// | 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置。 |
. | 選取當前節點。 |
… | 選取當前節點的父節點。 |
@ | 選取屬性。 |
根據元素的屬性定位
屬性值開頭和結尾:starts-with、ends-with
有些元素的ID、class等不固定,但是有些屬性的值是有規律的:
例如,某元素的src屬性中開頭的一部分是不會變的,那麼就可以使用starts-with這個xpath定位方法,即,元素以什麼開頭。那麼這個節點的最終定位就類似:
//iframe[starts-with(@src,"/a/b/c/page/userCreate.jsp")]。
與其配套的還有ends-with,也就是以某字符串結尾的元素。
屬性值包含:contains
//div[contains(@class,‘Number Skill’)]
**也可以用and or等添加邏輯運算來加強判斷條件
獲取節點的屬性值
xpath無法獲取到屬性,只能定位到節點。要獲取節點的屬性需要在元素後使用get_attribute()方法:
urls = browser.find_elements_by_xpath(xpath_urls)
url = urls[0].get_attribute(“placeholder”)
模擬鼠標操作
懸停:ActionChains(webdriver).move_to_element(element).perform()
單擊不放:ActionChains(webdriver).click_and_hold(element).perform()
雙擊:ActionChains(webdriver).double_click(element).perform()
右擊:ActionChains(webdriver).context_click(element).perform()
拖放:ActionChains(webdriver).drag_and_drop(source, target).perform()
在源元素上按下鼠標左鍵,然後移動到目標元素上釋放。
模擬鍵盤按鍵
from selenium.webdriver.common.keys import Keys #需要導入keys 類包。
send_keys(Keys.BACK_SPACE) 刪除鍵(BackSpace)
send_keys(Keys.SPACE) 空格鍵(Space)
send_keys(Keys.TAB) 製表鍵(Tab)
send_keys(Keys.ESCAPE) 回退鍵(Esc)
send_keys(Keys.ENTER) 回車鍵(Enter)
send_keys(Keys.CONTROL,‘a’) 全選(Ctrl+A)
send_keys(Keys.CONTROL,‘c’) 複製(Ctrl+C)
send_keys(Keys.CONTROL,‘x’) 剪切(Ctrl+X)
send_keys(Keys.CONTROL,‘v’) 粘貼(Ctrl+V)
對瀏覽器彈出框的針對性操作
參考:https://blog.csdn.net/kelanmomo/article/details/82886374
browser.switch_to_alert已經在Senlenium3.141版本上取消(可能低版本上還可以用,沒試過),取而代之的是支持更多的browser.switch_to.alert
因爲還有browser.switch_to.frame等操作,應該是把方法又提升了一級
其他用法有:
element = driver.switch_to.active_element
alert = driver.switch_to.alert
driver.switch_to.default_content()
driver.switch_to.frame(‘frame_name’)
driver.switch_to.frame(1)
driver.switch_to.frame(diver.find_elements_by_tag_name(“iframe”)[0])
driver.switch_to.parent_frame()
driver.switch_to.window(‘main’)