如何使用xpath提取多个标签的html脚本中的文本

金名

假设我有很多这样的html脚本:

<div style="clear:both" id="novelintro" itemprop="description">you are foolish!<font color=red size=4>I am superman!</font></div>

我想使用xpath提取文本:您很愚蠢!我是超人!

但是,如果我使用

xpath('//div[@id="novelintro"]/text()').extract()

我只能说“你很愚蠢!”

当我使用时:

xpath('//div[@id="novelintro"]/font/text()').extract()"

我只能得到“我是超人!”

因此,如果您只能使用一个xpath表达式来提取整个句子,那就是“您很愚蠢!我是超人!”

更不幸的是,在上面的html脚本中,它是“ <font>”标签,但是在我的其他脚本中,还有许多其他标签,例如:

提取“嗨,我爱你!” 在以下脚本中:<div style="clear:both" id="novelintro" itemprop="description">hi girl<legend >I love you!</legend></div>

提取“如果我嫁给你的母亲,那么我就是你的父亲!” 在以下脚本中:

<div style="clear:both" id="novelintro" itemprop="description">If I<legend > marry your mother<div>then I am your father!</div></legend></div>

如果您只能使用一个xpath表达式来适应所有的html脚本?

托玛拉克

您可以使用XPath的string()函数,该函数以递归方式将单个节点转换为字符串(可选.引用当前节点):

from scrapy.selector import HtmlXPathSelector

def node_to_string(node):
    return node.xpath("string(.)").extract()[0]

# ------------------------------------------------------

body = """<body>
  <div style="clear:both" id="novelintro" itemprop="description">you are foolish!<font color=red size=4>I am superman!</font></div>
  <div style="clear:both" id="novelintro2" itemprop="description">hi girl<legend >I love you!</legend></div>
  <div style="clear:both" id="novelintro3" itemprop="description">If I<legend > marry your mother<div>then I am your father!</div></legend></div>
</body>"""

hxs = HtmlXPathSelector(text=body)

# single target use
print node_to_string(hxs.xpath('//div[@id="novelintro"]'))
print 

# multi target use
for div in hxs.xpath('//body/div'):
    print node_to_string(div)
print 

# alternatively
print [node_to_string(n) for n in hxs.xpath('//body/div')]
print 

输出

你真傻!我是超人!

你真傻!我是超人!
嗨,女孩,我爱你!
如果我嫁给你母亲,那我就是你父亲!

['你真是愚蠢!我是超人!',你好,我爱你!',''如果我嫁给你的母亲,那我就是你的父亲!']

请注意,缺少空格,因为源中缺少空格。string()处理空白的方式与浏览器相同。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

xpath:如何提取“strong”标签中的文本?

如何使用XPATH从html提取文本

如何禁用html文本中的脚本标签?

使用BeautifulSoup仅从html提取脚本标签内容以外的文本

如何找到多个标签的动态xpath以及div中的文本

从Python中的脚本标签提取文本

使用Python从HTML中的脚本标签中提取数据

使用Python中的BeautifulSoup从HTML脚本标签中提取JSON

如何使用不带HTML标记的XPath提取文本?

从多个来源使用 xpath 提取文本

如何使用 BeautifulSoup 从 HTML div 标签文件中提取文本?

如何使用xpath和python提取包含不需要的BR标签的标签之间的文本?

当有多个相似标签时,使用 Beautiful Soup 从特定 HTML 标签中提取文本

如何使用xpath提取[无标签词]?

如何提取除脚本标签内的内容之外的所有 html 文本?

如何从html标签之间提取文本?

如何从<a> html标签提取超链接文本?

如何提取不带/不带文本的HTML标签

HTML XPath:提取混合了多级复杂标签的文本?

如何从多个网页中提取文本,其中某些页面的文本使用不同的标签?

从Perl中的HTMl / XML标签提取文本

如何使用 JQuery 替换脚本标签中的文本

如何从beautifulSoup中提取多个html标签?

如何使用XPath提取同一标签下的所有文本?

从html标签提取文本

如何使用imacros xpath提取特定文本

如果其他html在标签内,如何从div标签中提取python中的文本?

如何通过xpath提取html dom中的文本节点的文本?

使用带有标记的XPath提取标签之间的文本