鍍金池/ 問答/數(shù)據(jù)分析&挖掘  Python/ scrapy爬蟲xpath().extract()[0]獲取內(nèi)容報(bào)list in

scrapy爬蟲xpath().extract()[0]獲取內(nèi)容報(bào)list index out of range錯(cuò)

小弟新手,在看著教程寫scrapy爬蟲時(shí)使用xpath().extract()[0]的方法獲取內(nèi)容,報(bào)IndexError: list index out of range錯(cuò)誤,求問大神怎么解決,急求答案在線等。(試過去掉.extract()[0],會(huì)報(bào)出TypeError: Request url must be str or unicode錯(cuò)誤)。代碼如下:


cnblog_spider.py

# -*- coding:utf-8 -*-
# !/usr/bin/env python
import scrapy
from bs4 import BeautifulSoup
from scrapy import Selector

from p1.items import CnblogsSpiderItem


class CnblogsSpider(scrapy.spiders.Spider):
    name = "cnblogs" # 爬蟲的名稱
    allowed_domains = ["cnblogs.com"]# 允許的域名
    start_urls = [
        "http://www.cnblogs.com/qiyeboy/default.html? page=1"
    ]
    def parse(self,response):
        # 實(shí)現(xiàn)網(wǎng)頁(yè)的解析
        # 首先抽取所有的文章
        papers = response.xpath(".//*[@class='day']")#.extract()
        # 從每篇文章中抽取數(shù)據(jù)
        #soup = BeautifulSoup(papers, "html.parser", from_encoding="utf-8")
        # print papers
        for paper in papers:
            url = paper.xpath(".//*[@class='pastTitle']/a/@href").extract()[0]
            title = paper.xpath(".//*[@class='pastTitle']/a").extract()[0]
            time = paper.xpath(".//*[@class='dayTitle']/a").extract()[0]
            content = paper.xpath(".//*[@class='postCon']/a").extract()[0]
            # print url, title, time, content
            item = CnblogsSpiderItem(url=url, title=title, time=time, content=content)
            request = scrapy.Request(url=url, callback=self.parse_body)
            request.meta['item'] = item  # 將item暫存
            yield request
            #yield item
        next_page = Selector(response).re(u'<a href="(\S*)">下一頁(yè)</a>')
        if next_page:
            yield scrapy.Request(url=next_page[0], callback=self.parse)

    def parse_body(self, response):
        item = response.meta['item']
        body = response.xpath(".//*[@class='postBody']")
        item['cimage_urls'] = body.xpath('.//img//@src').extract()
        yield item

回答
編輯回答
青檸

先進(jìn)行非空判斷,在執(zhí)行業(yè)務(wù)邏輯,這個(gè)問題多半是沒有獲取到數(shù)據(jù)

2017年6月20日 05:48
編輯回答
真難過

應(yīng)該是沒爬到數(shù)據(jù)
最好的辦法是在xpath().extract()[0]打個(gè)斷點(diǎn),看看數(shù)據(jù)取到了沒
我以前也遇到過這種問題,是xpath寫的不對(duì),所以沒爬到頁(yè)面數(shù)據(jù)。

2018年8月15日 13:21
編輯回答
乖乖瀦

網(wǎng)頁(yè)的結(jié)構(gòu)發(fā)生了變化。
語(yǔ)句應(yīng)對(duì)應(yīng)修改為:
content = paper.xpath(".//*[@class='postCon']/div/text()").extract()[0]

2018年6月2日 07:55
編輯回答
神曲

超出列表范圍而且還是[0],那肯定就是空列表了,看看xpath是不是提取錯(cuò)了

2017年6月3日 02:23