1、先安装webdriver驱动文件
Chrome驱动文件下载:点击下载chromedrive
Firefox驱动文件下载:点解下载geckodriver
2、配置环境变量
3、selenium的8种定位方式
定位一个元素 定位多个元素 含义
find_element_by_id find_elements_by_id 通过元素id定位
find_element_by_name find_elements_by_name 通过元素name定位
find_element_by_xpath find_elements_by_xpath 通过xpath表达式定位
find_element_by_link_text find_elements_by_link_tex 通过完整超链接定位
find_element_by_partial_link_text find_elements_by_partial_link_text 通过部分链接定位
find_element_by_tag_name find_elements_by_tag_name 通过标签定位
find_element_by_class_name find_elements_by_class_name 通过类名进行定位
find_elements_by_css_selector find_elements_by_css_selector 通过css选择器进行定位
4、实例
以百度页面为例
from selenium import webdriver
from time import sleep
driver = "/Applications/PyCharm.app/Contents/bin/chromedriver" #chromedriver的相对路径
broser = webdriver.Chrome(executable_path=driver)
url = broser.get("https://www.baidu.com/")
username = broser.find_element_by_name("tj_login").send_keys("")
login = broser.find_element_by_css_selector(‘//*[@id="u1"]/a[7]‘).click()
aa = broser.find_element_by_id("kw").send_keys("hhhhh")
bb = broser.find_element_by_css_selector(‘#su‘).click()
cc = broser.find_element_by_css_selector(‘#u1 > a.lb‘).click()
sleep(3)
usernamelogin = broser.find_elements_by_css_selector(‘p.tang-pass-footerBarULogin‘)[0]
usernamelogin.click()
userName = broser.find_element_by_id(‘TANGRAM__PSP_10__userName‘).send_keys("手机号码")
pwd = broser.find_element_by_id(‘TANGRAM__PSP_10__password‘).send_keys("qwertyqfmQ")
login = broser.find_element_by_css_selector(‘#TANGRAM__PSP_10__submit‘).click()
sleep(2)
mima = broser.find_element_by_id(‘TANGRAM__39__input_label_vcode‘).send_keys("123456")
quding = broser.find_element_by_class_name(‘forceverify-button forceverify-button-send‘).click()
fasong = broser.find_element_by_xpath(‘//*[@id="TANGRAM__39__button_send_mobile"]‘).click()
mima = broser.find_element_by_xpath(‘//*[@id="TANGRAM__39__input_label_vcode"]‘).send_keys("522269")
queding = broser.find_element_by_css_selector(‘#TANGRAM__39__button_submit‘).click()
原文地址:https://www.cnblogs.com/shengxia0911/p/11073698.html