美文网首页
文字定位, 我选XPATH

文字定位, 我选XPATH

作者: halfempty | 来源:发表于2019-04-17 19:30 被阅读0次

前言

无论是玩爬虫, 还是自动化测试, 元素定位少不了
虽然CSS选择器效率更佳, 但天生不具备文字定位功能
加上前端编码不规范, 前端技术的革新(如vue), 好些css属性开始淡化, 可能通篇就一个id='app'
所以本人更倾向于xpath

  • 文字更直观, 更容易理解定位的对象
  • 前端组件化后, xpath可以更通用, 比如表单中的输入控件, 下拉框等

xpath文字定位

1. text() - 匹配文字

div[@id='app']这类属性定位大家应该很熟悉了, 就不赘述
下面截取豆瓣电影部分页面源码

在这里插入图片描述
导演/编剧的结构一样, 用xpath定位如下:
//span[text()='导演']
//span[text()='编剧']

2. 同级元素

如果要获取导演的具体信息, 可以结合following-sibling, 如果是同级往上,则使用preceding-sibling

following-sibling
Indicates all the nodes that have the same parent as the context node and appear after the context node in the source document.

preceding-sibling
Indicates all the nodes that have the same parent as the context node and appear before the context node in the source document.

//span[text()='导演']/following-sibling::span/a
//span[text()='编剧']/following-sibling::span/a

试想, 如果类似的属性都是相同结构, 只需要将文字作为参数, 就能定位到指定的数据

3. contains() - 文字包含

contains方法放宽文字匹配规则, 部分匹配即可, 更加灵活

4. normalize-space() - 去除空格

有时, 文字的前后有空格, 或者回车, 可以使用normalize-space方法去除

The normalize-space function strips leading and trailing white-space
from a string, replaces sequences of whitespace characters by a single
space, and returns the resulting string.

相关文章

  • 文字定位, 我选XPATH

    前言 无论是玩爬虫, 还是自动化测试, 元素定位少不了虽然CSS选择器效率更佳, 但天生不具备文字定位功能加上前端...

  • lxml模块

    lxml 模块 简介 xpath定位 详见xpath定位 lxml模块中使用xpath语法定位元素提取属性值或文本...

  • python3 selenium webdriver 元素定位-

    各种xpath定位方法以及xpath轴定位 //ul[starts-with(@id,"menu")]/li[2]...

  • 元素定位

    八大定位 Xpath定位 css定位

  • selenium使用Xpath+JavaScript+jQuer

    我们先了解一下Xpath基础语法,如下: xpath常用函数: 一.Xpath的定位方法(复制路径的定位经常会经常...

  • 定位工具

    FireFox:xpath checker Chrome:Xpath Finder 关于iframe的定位,Fir...

  • selenium的css定位与xpath定位

    大部分人在使用selenium定位元素时,用的是xpath定位,因为xpath基本能解决定位的需求。css定位往往...

  • 常用的xpath

    xpath的模糊查询 选取同级节点 获取父级节点 xpath定位 列表时间筛选 xpath获取标签 xpath的s...

  • Xpath定位方法深入探讨及元素定位失败常见情况

    一、Xpath定位方法深入探讨 (1)常用的Xpath定位方法及其特点 使用绝对路径定位元素。 例如: 特点:这个...

  • 元素定位-03 重点讲解css

    元素定位:CCS和xpath(做项目一般用css定位--抗变性强) xpath定位:根据路径定位,一层一层往下找的...

网友评论

      本文标题:文字定位, 我选XPATH

      本文链接:https://www.haomeiwen.com/subject/colowqtx.html