使用 xPath 提取文本 [英] Extract text with xPath

查看:50
本文介绍了使用 xPath 提取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 xPath 中遇到问题.

I have a problem in xPath.

我这样做:

//tbody/tr[td]*[2]/span/@onmouseover

结果:

showMsgBox('Monster')
showMsgBox('Limber')
showMsgBox('Carson')
showMsgBox('Maniac')

我需要文本,我可以提取不同的文本吗?.我在 Chrome 中使用刮刀.谢谢大家.

I need text, Can I extract different texts?. I'm using scraper in Chrome. Thanks all.

推荐答案

所以看起来你的 HTML 结构是这样的:

So it looks like you have an HTML structure like this:

<tbody>
  <tr>
    <td>
      <span onmouseover="showMsgBox('Monster')"></span>
    </td>
  </tr>
</tbody>

而你正试图摆脱Monster.

由于你没有分享你的 HTML,我快速尝试复制一些类似的东西.这是为了说明,与您的不完全匹配.

仅使用 XPath 无法做到这一点.XPath 允许您在 DOM 中选择节点.在此 HTML 中使用 XPath 可以达到的最低级别正是您已经拥有的:

You cannot do this with just XPath. XPath allows you to select nodes in the DOM. The lowest level you can reach with XPath in this HTML is exactly what you already have:

//tbody/tr[td]*[2]/span/@onmouseover

哪个返回

showMsgBox('Monster')

如果您想从中提取Monster,您必须使用不同的机制,例如简单的字符串操作或正则表达式.

If you want to extract Monster from that you'll have to use a different mechanism, such as simple string manipulation or a regular expression.

var text = "showMsgBox('Monster')";
text = text.substring( "showMsgBox('".length );
text = text.substring(0, text.length - "')".length);

或者如果你不介意魔法常数:

Or if you don't mind magic constants:

var text = "showMsgBox('Monster')";
text = text.substring(12);
text = text.substring(0, text.length - 2);

或者在使用 slice 的单个操作中:

Or in a single operation using slice:

text.slice(12, -2)

正则表达式

您也可以使用正则表达式来提取文本,但我认为这不会让这里的情况变得更好.

Regular expression

You could also use a regular expression to extract the text, but I don't feel that would make things much better here.

var text = "showMsgBox('Monster')";
new RegExp("showMsgBox\\('(.*)'\\)").exec(text)[1]

/showMsgBox\('(.*)'\)/.exec(text)[1]

这篇关于使用 xPath 提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆