selenium之定位元素
id、name、class、xpath、css、link_text、partial_link_text、tag_name
一、查看元素的属性
(1)通过f12+fn 或f12 或者更多工具-开发工具
根居属性进行定位
二、定位实战
1、id定位
from selenium import webdriver
from time import *
dx=webdriver.Chrome()
dx.get("https://www.baidu.com/")
sleep(2)
dx.maximize_window()
dx.find_element_by_id("kw").send_keys("id定位")
2、name定位
from selenium import webdriver
from time import *
dx=webdriver.Chrome()
dx.get("https://www.baidu.com/")
sleep(2)
dx.maximize_window()
dx.find_element_by_name("wd").send_keys("name定位")
3、class name定位
from selenium import webdriver
from time import *
dx=webdriver.Chrome()
dx.get("https://www.baidu.com/")
sleep(2)
dx.maximize_window()
dx.find_element_by_class_name("s_ipt").send_keys("class定位")
4、link_text 链接定位
from selenium import webdriver
from time import *
dx=webdriver.Chrome()
dx.get("https://www.baidu.com/")
sleep(2)
dx.maximize_window()
dx.find_element_by_link_text("hao123").click()
5、模糊匹配
find_element_by_partial_link_text
from selenium import webdriver
from time import *
dx=webdriver.Chrome()
dx.get("https://www.baidu.com/")
sleep(2)
dx.maximize_window()
dx.find_element_by_partial_link_text("hao").click()
dx.find_element_by_partial_link_text("AI").click()
dx.find_element_by_partial_link_text("新闻").click()
dx.find_element_by_partial_link_text("地图").click()
dx.find_element_by_partial_link_text("贴吧").click()
dx.find_element_by_partial_link_text("视频").click()
dx.find_element_by_partial_link_text("图片").click()
6、xpath定位
复制的xpath://*[@id="kw"]
from selenium import webdriver
from time import *
dx=webdriver.Chrome()
dx.get("https://www.baidu.com/")
sleep(2)
dx.maximize_window()
dx.find_element_by_xpath('//*[@id="kw"]').send_keys("xpath定位")
7、css定位
复制css :#kw
from selenium import webdriver
from time import *
dx=webdriver.Chrome()
dx.get("https://www.baidu.com/")
sleep(2)
dx.maximize_window()
dx.find_element_by_css_selector("#kw").send_keys("css定位方法")
8、js定位方法
from selenium import webdriver
from time import *
dx=webdriver.Chrome()
dx.get("https://www.baidu.com/")
sleep(2)
dx.maximize_window()
js="document.getElementById('kw').value='js定位'"
dx.execute_script(js)
9、tag_name 标签名称定位
from selenium import webdriver
from time import *
dx=webdriver.Chrome()
dx.get("https://www.baidu.com/")
sleep(2)
dx.maximize_window()
inputs=dx.find_elements_by_tag_name("input")
for i in inputs:
if i.get_attribute("name")=="wd":
i.send_keys("tag_name定位")