谷歌浏览器,以百度一下页面为例,定位“新闻”链接
python代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
# name
driver.find_element_by_name("tj_trnews").click()
#class
driver.find_elements_by_class_name("mnav")[0].click()
#link text
driver.find_element_by_link_text("新闻").click()
#partial link text
driver.find_element_by_partial_link_text("新").click()
#xpath 0
driver.find_element_by_xpath("//a[@name='tj_trnews']").click()
driver.find_element_by_xpath("//*[@name='tj_trnews']").click()
#xpath 1
driver.find_element_by_xpath("//div[@id='u1']/a[1]").click()
#xpath 2
driver.find_element_by_xpath("//div[@class='head_wrapper']/div[3]/a[1]").click()
#xpath 3
driver.find_element_by_xpath("//a[contains(text(),'新')]").click()
#xpath 4
driver.find_element_by_xpath("//a[contains(@href,'news.baidu.com')]").click()
#css
driver.find_element_by_css_selector("#u1 > a:nth-child(1)").click()
time.sleep(3)
driver.quit()
8种定位方式:
1、利用ID定位元素:find_element_by_id("kw")
2、利用tag name定位:find_element_by_tag_name("form") #很少用,tag name就是标签名,如<input> <form>
3、利用link text定位:find_element_by_link_text("新闻")
find_element_by_xpath("//*[@id='u1']/a[text()='新闻']")
4、partial link text定位:driver.find_element_by_partial_link_text("新").click()
5、class name定位:find_element_by_class_name("s_ipt").send_keys("selenium")
6、name定位:driver.find_element_by_name("wd").send_keys("selenium")
从准确性来说,id>name>class,很多元素是无法通过id ,css, text, name来直接定位这个网页元素,更多的还是根据XPath或者css表达式去定位。
7、css定位:driver.find_element_by_css_selector("#kw")
8、xpath:driver.find_element_by_xpath("//*[@id = 'kw']")
Xpath详细:
1.绝对路径定位 find_element_by_xpath(“html/body/div/div[2]/div/div/div/form/span/input”)
div[2]表示当前层级下的第二个div标签
2.相对路径,以"//"开头
3.利用元素属性 find_element_by_xpath(“//input[@id=’kw’]”)
find_elements_by_xpath("//*[@type='radio']")
//表示当前页面某个目录下,input为标签名,如果不想指定标签名,可用星号(*)代替,不局限于id,能唯一标识元素的任意属性都可以
4.层级与属性结合 find_element_by_xpath(“//span[@class=’bg’]/apan[2]/input”)
5.使用逻辑运算符 find_element_by_xpath(“//input[@id=’kw’ and class=’su’]/span/input”)
6.使用标签中的文本值 find_element_by_xpath("//a[contains(text(),'关于百度')]")
当标签属性很少,不足以唯一区别元素时,但是标签中存在唯一的文本值,也可以定位
如何获取xpath和css
方法一:打开chrome开发者工具,左上角有个箭头,可以在页面中选取元素。定位到代码后左击copy-->copy Xpath,copy-->copy selector
方法二:使用工具selectGadget
这个工具是提取xpath路径的
离线下载-->打开谷歌扩展程序chrome://extensions/-->将crx插件文件拖入安装-->浏览器右上角有一个搜索按钮,即可以使用
clear:清除本次操作,重新开始
toggle:将工具栏上下调换位置
Xpath:提取选中目标的Xpath路径
当鼠标选中目标后,目标变成绿色,而其它变成黄色。黄色和绿色都是被选中状态,如果想只选绿色,那么再次点击黄色就可以去掉,此时黄色变成了红色。