首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用lxml.html与BeautifulSoup定位元素

使用lxml.html与BeautifulSoup定位元素
EN

Stack Overflow用户
提问于 2011-04-23 22:24:21
回答 1查看 856关注 0票数 0

我正在使用lxml.html抓取一个html文档;在BeautifulSoup中有一件事我可以做,但是用lxml.htm做不到。这就是它:

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-04-23 23:17:43

通过使用EXSLT syntax,可以在lxml中使用正则表达式。例如,给定您的文档,这将选择其文本与正则表达式spe.*al匹配的父节点

代码语言:javascript
复制
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})

输出:

代码语言:javascript
复制
[<Element table at 7fe21acd3f58>]
[<Element p at 7f76ac2c3f58>, <Element table at 7f76ac2e6050>]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5764721

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档