假设我有很多这样的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] 删除。
我来说两句