安装selenium包:
cmd > pip install selenium
安装与浏览器相匹配的浏览器驱动
导包:
from selenium import webdriver
获取浏览器驱动:
dr = webdrover.Chrome()
打开被测试系统的页面
dr.get('https://www.so.com/')
元素定位:
1.根据id定位:
定位输入框位置:
inputBox = dr.find_element_by_id('input')
向输入框中输入内容:
inputBox.sned_keys('selenium自动化')
2.根据name定位:
dr.find_element_by_name('q').sned_keys('selenium自动化')
3.根据class_name定位:
dr.find_element_by_class_name('placeholder').sned_keys('selenium自动化')
4.根据link_text定位:
dr.find_element_by_link_text('资讯').click()
5.根据partial_link_text定位:
dr.find_element_by_partial_link_text('官网').click()
6.根据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.根据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)多个元素属性定位:
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.根据css定位:
(1)class定位:
dr.find_element_by_css_selector('.placeholder').send_keys('selenium自动化')
(2)根据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,'官网').click()
dr.find_element(By.TEG_NAME,'标签名')
dr.find_element(By.XPATH,'//input[@id = "input"]').send_keys('selenium自动化')
dr.find_element(By.CSS_SELECTOR,'[id = input]').send_keys('selenium自动化')