安裝selenium包:
cmd > pip install selenium
安裝與瀏覽器相匹配的瀏覽器驅(qū)動
導(dǎo)包:
from selenium import webdriver
獲取瀏覽器驅(qū)動:
dr = webdrover.Chrome()
打開被測試系統(tǒng)的頁面
dr.get('https://www.so.com/')
元素定位:
1.根據(jù)id定位:
定位輸入框位置:
inputBox = dr.find_element_by_id('input')
向輸入框中輸入內(nèi)容:
inputBox.sned_keys('selenium自動化')
2.根據(jù)name定位:
dr.find_element_by_name('q').sned_keys('selenium自動化')
3.根據(jù)class_name定位:
dr.find_element_by_class_name('placeholder').sned_keys('selenium自動化')
4.根據(jù)link_text定位:
dr.find_element_by_link_text('資訊').click()
5.根據(jù)partial_link_text定位:
dr.find_element_by_partial_link_text('官網(wǎng)').click()
6.根據(jù)teg定位:
inputBoxes = dr.find_element_by_teg_name('input')
print(len(inputBoxes))
print(inputBoxes)
for inputBox in inputBoxes:
if inputBox.get_attribute('class') == 'placeholder' and inputBox.get_attribute('suggestwidth') == '540px'
inputBox.send_keys('selenium自動化')
7.根據(jù)xpath定位:
(1)絕對路徑定位:
dr.find_element_by_xpath('/html/body/div[2]/div/section[2]/div/form/fieldset/div[2]/input').send_keys('selenium自動化')
(2)相對路徑定位:
1)元素屬性定位:
dr.find_element_by_xpath('//input[@suggestwidth = "540px"]').send_keys('selenium自動化')
dr.find_element_by_xpath('//*[@suggestwidth = "540px"]').send_keys('selenium自動化')
2)多個(gè)元素屬性定位:
dr.find_element_by_xpath('//input[@class = "placeholder" and @name = "q"]').send_keys('selenium自動化')
3)屬性層次定位:
dr.find_element_by_xpath('//div[@class = "skin-search-input hover"]/input[@class = "placeholder"]').send_keys('selenium自動化')
8.根據(jù)css定位:
(1)class定位:
dr.find_element_by_css_selector('.placeholder').send_keys('selenium自動化')
(2)根據(jù)id定位:
dr.find_element_by_css_selector('#input').send_keys('slelnium自動化')
引入By類
from selenium.webdriver.common.by import By
dr.find_element(By.ID,'input').send_keys('element自動化')
dr.find_element(By.CLASS_NAME,'placeholder').send_keys('selenium自動化')
dr.find_element(By.NAME,'q').send_keys('selenium自動化')
dr.find_element(By.LINK_TEXT,'資訊').click()
dr.find_element(By.PARTIAL_LINK_TEXT,'官網(wǎng)').click()
dr.find_element(By.TEG_NAME,'標(biāo)簽名')
dr.find_element(By.XPATH,'//input[@id = "input"]').send_keys('selenium自動化')
dr.find_element(By.CSS_SELECTOR,'[id = input]').send_keys('selenium自動化')