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

2024-09-30 20:27:10 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有很多这样的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脚本?在


Tags: div脚本youidstylehtmldescriptionxpath
2条回答

如果您的文档是:

<outer>This is outer text.<inner>And this is inner text.</inner>More outer text.</outer>

使用xpath表达式:/outer//text() (阅读:“outer”下面的任何文本),结果是一个如下所示的列表:

This is outer text. - And this is inner text. - More outer text.

可以使用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 

输出

^{pr2}$

请注意,由于源代码中缺少空格,因此缺少空格。string()处理空白的方式与浏览器相同。在

相关问题 更多 >