如何使用scrapy选择下一个节点

问题描述 投票:10回答:2

我有html看起来像这样:

<h1>Text 1</h1>
<div>Some info</div>
<h1>Text 2</h1>
<div>...</div>

我理解如何使用h1中的scrapy信息提取:

content.select("//h1[contains(text(),'Text 1')]/text()").extract()

但我的目标是从<div>Some info</div>中提取内容

我的问题是我没有关于div的任何具体信息。所有我所知道的,它正好在<h1>Text 1</h1>之后。我可以使用选择器在树中获取NEXT元素吗?元素,位于DOM树中的同一级别?

就像是:

a = content.select("//h1[contains(text(),'Text 1')]/text()")
a.next("//div/text()").extract()
Some info
python html parsing dom scrapy
2个回答
16
投票

试试这个xpath

//h1[contains(text(), 'Text 1')]/following-sibling::div[1]/text()

0
投票

使用following-sibling。来自https://www.w3.org/TR/2017/REC-xpath-31-20170321/

以下兄弟轴包含上下文节点的以下兄弟节点,上下文节点的父节点的子节点按文档顺序出现在上下文节点之后;

例:

from scrapy.selector import Selector
text = '''
<h1>Text 1</h1>
<div>Some info</div>
<h1>Text 2</h1>
<div>...</div>
'''
sel = Selector(text=text)
h1s = sel.xpath('//h1/text()')
for counter, h1 in enumerate(h1s,1):
    div = sel.xpath('(//h1)[{}]/following-sibling::div[1]/text()'.format(counter))
    print(h1.get())
    print(div.get())

输出是:

Text 1
Some info
Text 2
...
© www.soinside.com 2019 - 2024. All rights reserved.