Python lxml html xpath正则表达式解析

时间:2017-07-01 12:59:42

标签: python html regex xpath lxml

我在Python 3.6中的lxml etree.XPath表达式中使用正则表达式时出现问题

在此示例中,我在 stackoverflow 主页上搜索由空格包围的4位数字。并返回该元素的xpath

我得到的比赛只是白色空间。我似乎无法过滤掉它们。我的感觉是它可能是一些编码问题,但不能指责它......

下图来自https://regex101.com/。正确地给我一场比赛。

这是主页html的链接: https://drive.google.com/open?id=0B3HIB_5rVAxmZU9ialZHdzhscE0

enter image description here

这是我的代码

from lxml import html
from lxml import etree

with open('stackoverflow.html', 'r', encoding='utf8') as f:
    page_html = f.read()

html_tree = html.fromstring(page_html)

regexpNS = "http://exslt.org/regular-expressions"
find = etree.XPath("//*[re:test(., '(\s\d{4}\s)', 'i')]",
                       namespaces={'re':regexpNS})

tree = etree.fromstring(page_html)
tree = etree.ElementTree(tree)
for element in find(tree):
    text = str(element.text)
    str(text).strip()
    if text != '':
        print(text)
        print(len(text))
        print(tree.getpath(element))
        print('##############################################################')

输出

    None
    4
    / *
    ##############################################################

    13
    / * / *[2]
    ##############################################################

    13
    / * / *[2] / * [8]
    ##############################################################

    17
    / * / *[2] / * [8] / *
    ##############################################################

    21
    / * / *[2] / * [8] / * / *
    ##############################################################

    25
    / * / *[2] / * [8] / * / * / * [18]
    ##############################################################

    29
    / * / *[2] / * [8] / * / * / * [18] / *
    ##############################################################

    33
    / * / *[2] / * [8] / * / * / * [18] / * / * [2]
    ##############################################################
    site
    design / logo © 2017
    Stack
    Exchange
    Inc;
    user
    contributions
    licensed
    under
    117
    / * / *[2] / * [8] / * / * / * [18] / * / * [2] / *
    ##############################################################

带有len>的空白文字行怎么回事?应该被剥离的0 ???

谢谢!

1 个答案:

答案 0 :(得分:0)

str.strip会返回已剥离的文字,但不会更改text

>>> text = '    a    '
>>> text.strip()   # returns a new string
'a'
>>> text  # `text` is not changed
'    a    '

如果您想要更改text,则需要将上述表达式的返回值重新分配回text(顺便说一句,您不需要调用str(..)因为{{1} }}已经是text对象:

str

应替换为:

str(text).strip()
相关问题