webdirver初识_8种元素定位方法
webdriver提供八种元素定位方法:
前提:安装python, vscode, selenium, webdriver(谷歌浏览器驱动)
from selenium import webdriver
from time import sleep
dr = webdriver.Chrome()
dr.get("https://www.baidu.com") #打开百度页面
#send_keys()
dr.find_element_by_id("kw").send_keys("selenium") #定位搜索框,输入selenium
dr.find_element_by_id("su").click() #点击“百度一下”进行搜索
#title 和url:
title1 = dr.title #获取当前页面title
print(title1)
now_url = dr.current_url #获取当前页面url
print(now_url)
try:
assert 'selenium22' in now_url
except AssertionError:
print("用例失败")
#定位单个文本:
result_text = dr.find_element_by_class_name("nums_text").text
print(result_text)
#获取一组元素:用elements
result_texts = dr.find_elements_by_css_selector("div > h3 > a")
for i in result_texts:
print(i.text)
#result_texts = dr.find_elements_by_css_selector("div > h3 > a").text #一组数据后不可以在后面直接加.text 会报错
dr.quit()