我认为这个问题可能有一个简单的解决方案...我想做的就是使用我的变量项 ['genre'] 提取列出流派类型的文本,足够简单...但是,作为我提取的项目仅出现在我正在抓取的页面上,当循环遍历其他项目(例如项目['artist'])时,不包括项目['流派']。任何帮助,将不胜感激。这是我认为相关的代码。
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 包含另一个 div,该 div 具有 class="header"
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()
关于python - 项目不包含在 Scrapy 中的 for 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29570682/