Thi*_*ode 5 python xpath lxml lowercase html-parsing
我试图lower-case在XPath中使用函数匹配国家或国家.translate有点凌乱,所以使用小写和我的Python版本2.6.6具有XPath 2.0支持我相信,因为小写只在XPath 2.0中可用.
我如何能在我的案例中使用小写字符是我正在寻找的.希望这个例子是自我解释的.我正在寻找['USA', 'US']输出(两个国家一次性如果小写评估国家和国家是相同的,可能会发生).
HTML:doc.htm
<html>
<table>
<tr>
<td>
Name of the Country : <span> USA </span>
</td>
</tr>
<tr>
<td>
Name of the country : <span> UK </span>
</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
Python:
import lxml.html as lh
doc = open('doc.htm', 'r')
out = lh.parse(doc)
doc.close()
print out.xpath('//table/tr/td[text()[contains(. , "Country")]]/span/text()')
# Prints : [' USA ']
print out.xpath('//table/tr/td[text()[contains(. , "country")]]/span/text()')
# Prints : [' UK ']
print out.xpath('//table/tr/td[lower-case(text())[contains(. , "country")]]/span/text()')
# Prints : [<Element td at 0x15db2710>]
Run Code Online (Sandbox Code Playgroud)
更新:
out.xpath('//table/tr/td[text()[contains(translate(., "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") , "country")]]/span/text()')
Run Code Online (Sandbox Code Playgroud)
现在问题仍然存在,我可以将翻译部分存储为全局变量'handlecase'并在每次执行XPath时打印该全局变量吗?
像这样的东西有效:
handlecase = """translate(., "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")"""
out.xpath('//table/tr/td[text()[contains(%s , "country")]]/span/text()' % (handlecase))
Run Code Online (Sandbox Code Playgroud)
但为了简单和可读性,我想像这样运行它:
out.xpath('//table/tr/td[text()[contains(handlecase , "country")]]/span/text()')
Run Code Online (Sandbox Code Playgroud)
我相信获得你想要的最简单的东西就是编写一个XPath扩展函数.
通过这样做,您可以编写lower-case()函数或不区分大小写的搜索.
您可以在此处找到详细信息:http://lxml.de/extensions.html
使用:
//td[translate(substring(text()[1], string-length(text()[1]) - 9),
'COUNTRY :',
'country'
)
=
'country'
]
/span/text()
Run Code Online (Sandbox Code Playgroud)
基于 XSLT 的验证:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:copy-of select=
"//td[translate(substring(text()[1], string-length(text()[1]) - 9),
'COUNTRY :',
'country'
)
=
'country'
]
/span/text()
"/>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
当此转换应用于提供的 XML 文档时:
<html>
<table>
<tr>
<td>
Name of the Country : <span> USA </span>
</td>
</tr>
<tr>
<td>
Name of the country : <span> UK </span>
</td>
</tr>
</table>
</html>
Run Code Online (Sandbox Code Playgroud)
计算 XPath 表达式并将选定的两个文本节点复制到输出:
USA UK
Run Code Online (Sandbox Code Playgroud)
解释:
ends-with($text, $s):这是:……
$s = substring($text, string-length($text) - string-length($s) +1)
Run Code Online (Sandbox Code Playgroud)
.2. 下一步是使用该translate()函数将结尾的 10 个字符长字符串转换为小写,消除任何空格或任何“:”字符。
.3. 如果结果是字符串(全部小写)“country”,那么我们选择spanthis 的 s= 子节点的子文本节点(本例中只有一个) td。