1. 程式人生 > >Python練習 scrapy 爬取汽車之家文章

Python練習 scrapy 爬取汽車之家文章

autohome.py  #spider檔案

# -*- coding: utf-8 -*-
import scrapy
from Autohome.items import AutohomeItem

class AutohomeSpider(scrapy.Spider):
    name = 'autohome'
    allowed_domains = ['https://www.autohome.com.cn/all/']
    start_urls = ['https://www.autohome.com.cn/all/']

    def parse(self, response):
#返回該表示式對應的所有selector list列表
        tit_list = response.xpath("//div[@class='article-wrapper']/ul/li/a")
        for tit in tit_list:
            item = AutohomeItem()
            #extract()序列化為unicode字串
            title = tit.xpath("./h3").extract()
            url = tit.xpath("./@href").extract()
            jianjie = tit.xpath("./p").extract()

            item['url'] = url[0]
            item['jianjie'] = jianjie[0]
            item['title'] = title[0]
            #返回提取到的每個item資料,傳給管道處理,同時還會回來繼續處理下一個資料
            yield item


#網址 //div[@class='article-wrapper']/ul/li/a/@href
#標題 //div[@class='article-wrapper']/ul/li/a/h3
#簡介 //div[@class='article-wrapper']/ul/li/a/p
Pipelines.py  管道檔案
import json

class AutohomePipeline(object):
    def __init__(self):
#建立檔案,以二進位制格式存入
        self.f = open("autohomet.json","wb")
#獲取到每一個item,
    def process_item(self, item, spider):
#json.dumps無法直接轉item,所以需要把item強制轉換成dict,即可操作。
#ensure_ascii,json.jump預設為ascii碼,所以需要改為false來顯示中文
        content = json.dumps(dict(item),ensure_ascii = False) + ",\n"
#把content以utf-8的形式寫入
        self.f.write(content.encode("utf-8"))
#把item返回給引擎,告訴引擎可以處理下一個item資料了。所有item資料處理完畢,
# 執行下面關閉方法
        return item

    def close_spider(self,spider):
        self.f.close()
items.py 
import scrapy


class AutohomeItem(scrapy.Item):
    # define the fields for your item here like:
    # 標題
    title = scrapy.Field()
    # 網址
    url = scrapy.Field()
    # 簡介
    jianjie = scrapy.Field()