我试图在XPath中使用lower-case
函数来匹配国家或国家。 translate
有点麻烦,所以使用小写字母和我的Python版本2.6.6具有XPath 2.0支持我相信因为小写字母只在XPath 2.0中可用。如何使用lxml进行Python XPath不区分大小写的搜索?
我如何在我的情况下使用小写字母是我正在寻找的。希望这个例子是自我解释的。我正在寻找['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>
的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>]
更新:
out.xpath('//table/tr/td[text()[contains(translate(., "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") , "country")]]/span/text()')
现在的追求离子仍然存在,我可以存储为一个全局变量“handlecase”翻译部分,打印全局变量每当我做一个XPath?
事情是这样工作的:
handlecase = """translate(., "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")"""
out.xpath('//table/tr/td[text()[contains(%s , "country")]]/span/text()' % (handlecase))
但是为了简单性和可读性的缘故,我想是这样运行:
out.xpath('//table/tr/td[text()[contains(handlecase , "country")]]/span/text()')
从[lxml XPath文档](http://lxml.de/xpathxslt.html):'lxml支持XPath 1.0';因此,使用lxml,您会被翻译卡住。 –
在这种情况下,我不确定为什么当我使用小写字母时不会抱怨。在这个示例场景中,我对翻译没有太大的好运。谢谢! – ThinkCode
[可能的重复](http://stackoverflow.com/questions/9804281/selectnodes-with-xpath-ignoring-cases/9805020#9805020) – JWiley