繁体   English   中英

Scrapy中的for循环中不包含的项目

[英]Item not included in for loop made in Scrapy

我认为可能有一个解决此问题的简单方法...我要做的就是提取文本,列出带有我的变量项目['genre']的类型类型,足够简单...但是,作为项目i我正在提取的内容仅出现在我要抓取的页面上,当循环浏览其他项目(例如“艺术家”)时,不包含项目“(体裁)”。 任何帮助,将不胜感激。 这是我认为是相关的代码。

def parse_item(self, response):#http://stackoverflow.com/questions/15836062/scrapy-crawlspider-doesnt-crawl-the-first-landing-page
    for info in response.xpath('//div[@class="entry vevent"] | //div[@id="page"]'):
        item = TutorialItem() # Extract items from the items folder.
        item ['artist'] = info.xpath('.//span[@class="summary"]//text()').extract() # Extract artist information.
        item ['date'] = info.xpath('.//span[@class="dates"]//text()').extract() # Extract date information.
        preview = ''.join(str(s)for s in item['artist'])
        item ['genre'] = info.xpath('.//div[@class="header"]//text()').extract()

真希望这是有道理的,否则请您道歉!

之所以只获得一种流派 ,是因为response.xpath('//div[@class="entry vevent"] | //div[@id="page"]')的返回列表将包含一个div(带有id =“ page”)和一堆div(带有class =“ entry vevent”)

在遍历上面的列表时, div[@id="page"]将满足类型 xpath,

即,该div包含另一个具有class =“ header”的 div

In [1]: a = response.xpath('//div[@class="entry vevent"] | //div[@id="page"]')

In [2]: a[0].xpath('.//div[@class="header"]//text()').extract()
Out[2]: [u'Clubbing Overview']

In [3]: a[1].xpath('.//div[@class="header"]//text()').extract()
Out[3]: []

In [4]: a[2].xpath('.//div[@class="header"]//text()').extract()
Out[4]: []
...

而在另一侧div [@ class =“ entry vevent”]上 ,它不包含任何具有class =“ header”的 div ,因此最终将导致获得空列表作为输出

说得通 ?

一种解决方案是将流派的 xpath放在循环之外,也可以将流派的 xpath修改为

info.xpath('.//div[@class="header"]//text() | ./parent::div[@class="rows"]/preceding-sibling::div[@class="header"]//text()').extract()

我认为您错过了循环结束时的return item

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM