1. 程式人生 > >使用scrapy第一次成功爬出信息,目標是流放之路論壇

使用scrapy第一次成功爬出信息,目標是流放之路論壇

odin 亂碼 mage 程序 awl sharp name new pid

由於喜歡玩POE流放之路,所以用這個論壇試試自己的新技能

程序語句都做了註釋說明,下面是步驟

1.建立項目

scrapy startproject poebbs

2.建立爬蟲

cd poebbs
scrapy genspider poebd

3.編輯items.py

title = scrapy.Field()
bbslink = scrapy.Field()

4.編輯poebd.py

import scrapy
from poebbs.items import PoebbsItem #一定要記得導入item

class PoebdSpider(scrapy.Spider):
    name = ‘poebd‘
    allowed_domains = [‘http://bbs.17173.com‘]
    start_urls = [‘http://bbs.17173.com/forum-9987-1.html‘, #選擇了3頁內容來爬
‘http://bbs.17173.com/forum-9987-2.html‘, ‘http://bbs.17173.com/forum-9987-3.html‘ ] def parse(self, response): sites = response.css(‘.new‘) #需要的內容在class=’new‘內,所以就取了這個範圍 for site in sites: item = PoebbsItem() item[‘title‘] = site.css(‘.new .xst::text‘).extract_first() #這裏是兩個class,沒有標簽標識
item[‘bbslink‘] = site.css(‘.new a::attr(href)‘).extract()[2] #這個網址在同一個class下,低3個a標簽內,所以用這個語法 yield item

5.編輯settings.py

FEED_EXPORT_ENCODING =‘utf-8‘    #加入這兩句防止保存中文文件時亂碼
FEED_EXPORT_ENCODING = ‘gb18030‘

6.運行爬蟲

scrapy crawl poebd -o note.csv     #保存為表格文件

結果

技術分享圖片

2019-05-03

使用scrapy第一次成功爬出信息,目標是流放之路論壇