我正在使用lxml.html抓取一个html文档;在BeautifulSoup中有一件事我可以做,但是用lxml.htm做不到。这就是它:
from BeautifulSoup import BeautifulSoup
import re
doc = ['<html>',
'<h2> some text </h2>',
'<p> some more text </p>',
'<table> <tr> <td> A table</td> </tr> </table>',
'<h2> some special text </h2>',
'<p> some more text </p>',
'<table> <tr> <td> The table I want </td> </tr> </table>',
'</html>']
soup = BeautifulSoup(''.join(doc))
print soup.find(text=re.compile("special")).findNext('table')我在cssselect上试过了,但没有成功。关于如何使用lxml.html中的方法定位它,您有什么想法吗?
非常感谢,D
发布于 2011-04-23 23:17:43
通过使用EXSLT syntax,可以在lxml中使用正则表达式。例如,给定您的文档,这将选择其文本与正则表达式spe.*al匹配的父节点
import re
import lxml.html
NS = 'http://exslt.org/regular-expressions'
tree = lxml.html.fromstring(DOC)
# select sibling table nodes after matching node
path = "//*[re:test(text(), 'spe.*al')]/following-sibling::table"
print tree.xpath(path, namespaces={'re': NS})
# select all sibling nodes after matching node
path = "//*[re:test(text(), 'spe.*al')]/following-sibling::*"
print tree.xpath(path, namespaces={'re': NS})输出:
[<Element table at 7fe21acd3f58>]
[<Element p at 7f76ac2c3f58>, <Element table at 7f76ac2e6050>]https://stackoverflow.com/questions/5764721
复制相似问题