如何选择刮擦循环中的元素?

2024-09-30 10:39:55 发布

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

我试图通过在一个网站的元素循环,从他们创建项目。但是,循环返回每个项的整个响应列表,而不是单个项

网站代码:

<div id="resultsList">

<div class="result">
<div ...>
<p><b><a href="...">
<spctc>CONTENT I</spctc>
</a></b></p>
</div>
</div>

<div class="result">
<div ...>
<p><b><a href="...">
<spctc>CONTENT II</spctc>
</a></b></p>
</div>
</div>

...

</div>

我的spider代码(我必须先登录,所以spider在将登录的网站传递给scrape函数而不是parse函数之前,先执行一些函数):

def scrape(self, response):      
    for article in response.xpath('//div[@class="result"]'):
        item = Article() # Creating a new Article object
        item['title'] = article.xpath('//spctc/text()').extract()
        print(item)

        yield item

使用此代码,每个项目看起来都一样:

{'title': ['CONTENT I',
           'CONTENT II', ...]}

我想要第一件

{'title': ['CONTENT I']}

,第二项为

{'title': ['CONTENT II']}

等等


Tags: 项目函数代码divtitle网站resultcontent
2条回答
item['title'] = article.xpath('.//spctc/text()').extract()

成功了

尝试迭代文章列表。。。 article.xpath('//spctc/text()')

相关问题 更多 >

    热门问题