好久沒有寫爬蟲了,寫一個scrapy的小爬爬來抓取網易新聞,代碼原型是github上的一個爬蟲,最近也看了一點mongoDB,順便小用一下,體驗一下NoSQL是什么感覺。言歸正傳啊,scrapy爬蟲主要有幾個文件需要修改。這個爬蟲需要你裝一下mongodb數據庫和pymongo,進入數據庫之后,利用find語句就可以查看數據庫中的內容,抓取的內容如下所示:
~~~
{
"_id" : ObjectId("5577ae44745d785e65fa8686"),
"from_url" : "http://tech.163.com/",
"news_body" : [
"科技訊 6月9日凌晨消息2015",
"全球開發者大會(WWDC 2015)在舊",
"召開,網易科技進行了全程圖文直播。最新",
"9操作系統在",
"上性能得到極大提升,可以實現分屏顯示,也可以支持畫中畫功能。",
"新版iOS 9 增加了QuickType 鍵盤,讓輸入和編輯都更簡單快捷。在搭配外置鍵盤使用 iPad 時,用戶可以用快捷鍵來進行操作,例如在不同 app 之間進行切換。",
"而且,iOS 9 重新設計了 app 間的切換。iPad的分屏功能可以讓用戶在不離開當前 app 的同時就能打開第二個 app。這意味著兩個app在同一屏幕上,同時開啟、并行運作。兩個屏幕的比例可以是5:5,也可以是7:3。",
"另外,iPad還支持“畫中畫”功能,可以將正在播放的視頻縮放到一角,然后利用屏幕其它空間處理其他的工作。",
"據透露分屏功能只支持iPad Air2;畫中畫功能將只支持iPad Air, iPad Air2, iPad mini2, iPad mini3。",
"\r\n"
],
"news_from" : "網易科技報道",
"news_thread" : "ARKR2G22000915BD",
"news_time" : "2015-06-09 02:24:55",
"news_title" : "iOS 9在iPad上可實現分屏功能",
"news_url" : "http://tech.163.com/15/0609/02/ARKR2G22000915BD.html"
}
~~~
下面就是需要修改的文件:
1.spider 爬蟲文件,制定抓取規則主要是利用xpath
2.items.py 主要指定抓取的內容
3.pipeline.py 有一個指向和存儲數據的功能,這里我們還會增加一個store.py的文件,文件內部就是創建一個MongoDB的數據庫。
4.setting.py 配置文件,主要是配置代理、User_Agent、抓取時間間隔、延時等等
主要就是這幾個文件,這個scrapy照以前的爬蟲我增加了幾個新功能,一個是和數據庫鏈接實現存儲的功能,不在是存成json或者txt文件,第二個就是在spider中設置了follow = True這個屬性,意思就是在爬到的結果上繼續往下爬,相當于一個深搜的過程。下面我們看看源代碼。
一般首先我們寫的是items.py文件
~~~
# -*- coding: utf-8 -*-
import scrapy
class Tech163Item(scrapy.Item):
news_thread = scrapy.Field()
news_title = scrapy.Field()
news_url = scrapy.Field()
news_time = scrapy.Field()
news_from = scrapy.Field()
from_url = scrapy.Field()
news_body = scrapy.Field()
~~~
之后我們編寫的就是spider文件。我們可以隨便命名一個文件,因為我們調用爬蟲的時候只需知道它文件內部的爬蟲名字就可以了,也就是name = "news"這個屬性,我們這里的爬蟲名字叫做news。如果你需要使用這個爬蟲你可能需要修改以下Rule里的allow屬性,修改一下時間,因為網易新聞不會存儲超過一年時間的新聞。你可以將時間改為近期如果現在為15年8月你就可以修改為/15/08。
~~~
#encoding:utf-8
import scrapy
import re
from scrapy.selector import Selector
from tech163.items import Tech163Item
from scrapy.contrib.linkextractors import LinkExtractor
from scrapy.contrib.spiders import CrawlSpider,Rule
class Spider(CrawlSpider):
?name = "news"
?allowed_domains = ["tech.163.com"]
?start_urls = ['http://tech.163.com/']
?rules = (
??? ?Rule(
??? ??? ?LinkExtractor(allow = r"/15/06\d+/\d+/*"),
??? ??? ?#代碼中的正則/15/06\d+/\d+/*的含義是大概是爬去/15/06開頭并且后面是數字/數字/任何格式/的新聞
??? ??? ?callback = "parse_news",
??? ??? ?follow = True
??? ??? ?#follow=ture定義了是否再爬到的結果上繼續往后爬
??? ??? ?),
??? ?)
?def parse_news(self,response):
??? ?item = Tech163Item()
??? ?item['news_thread'] = response.url.strip().split('/')[-1][:-5]
??? ?self.get_title(response,item)
??? ?self.get_source(response,item)
??? ?self.get_url(response,item)
??? ?self.get_news_from(response,item)
??? ?self.get_from_url(response,item)
??? ?self.get_text(response,item)
??? ?return item
?def? get_title(self,response,item):
??? ?title = response.xpath("/html/head/title/text()").extract()
??? ?if title:
??? ??? ?item['news_title'] = title[0][:-5]
?def get_source(self,response,item):
??? ?source = response.xpath("//div[@class='ep-time-soure cDGray']/text()").extract()
??? ?if source:
??? ??? ?item['news_time'] = source[0][9:-5]
?def get_news_from(self,response,item):
??? ?news_from = response.xpath("//div[@class='ep-time-soure cDGray']/a/text()").extract()
??? ?if news_from:
??? ??? ?item['news_from'] = news_from[0]
?def get_from_url(self,response,item):
??? ?from_url = response.xpath("//div[@class='ep-time-soure cDGray']/a/@href").extract()
??? ?if from_url:
??? ??? ?item['from_url'] = from_url[0]
?def get_text(self,response,item):
??? ?news_body = response.xpath("//div[@id='endText']/p/text()").extract()
??? ?if news_body:
??? ??? ?item['news_body'] = news_body
?def get_url(self,response,item):
??? ?news_url = response.url
??? ?if news_url:
??? ??? ?item['news_url'] = news_url
~~~
之后我們創建一個store.py的文件,在這個文件里我們創建了一個數據庫,之后會在pipeline文件中引用這個數據庫,將數據存儲在數據庫中。下面我們看看源代碼。
~~~
import pymongo
import random
HOST = "127.0.0.1"
PORT = 27017
client = pymongo.MongoClient(HOST,PORT)
NewsDB = client.NewsDB
~~~
在pipeline.py文件中,我們將import NewsDB這個數據庫,利用update語句將每一條新聞插入這個數據庫,其中還有兩個判斷一個是判斷爬蟲的名字是否為news另一個是判斷線程的編號是否為空,其中最重要的一句就是NewsDB.new.update(spec,{"$set":dict(item)},upsert = True),將字典中的數據插入到數據庫中。
~~~
from store import NewsDB
class Tech163Pipeline(object):
def process_item(self, item, spider):
if spider.name != "news":
return item
if item.get("news_thread",None) is None:
return item
spec = {"news_thread":item["news_thread"]}
NewsDB.new.update(spec,{"$set":dict(item)},upsert = True)
return None
~~~
最后我們會更改一下配置文件設置一下USER_AGENT,我們要最大程度的讓爬蟲模仿瀏覽器的行為,這樣才能順利抓取的你想要的內容。
~~~
BOT_NAME = 'tech163'
SPIDER_MODULES = ['tech163.spiders']
NEWSPIDER_MODULE = 'tech163.spiders'
ITEM_PIPELINES = ['tech163.pipelines.Tech163Pipeline',]
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'tech163 (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.7'
DOWNLOAD_TIMEOUT = 15
~~~