Scrapy是一個非常強大的爬蟲框架,只需極少代碼便可應(yīng)付一個簡單爬蟲型檀。
但如果需要幾十萬幾百萬的數(shù)據(jù)量冗尤,中間一旦有中斷,重新爬取則太浪費時間。
本文介紹一種思路裂七,結(jié)合mysql皆看,實現(xiàn)斷點重爬的方式。
以國外美食網(wǎng)站Yelp為例背零,指定爬取香港的所有餐廳信息:餐廳名稱腰吟、地址、評價等信息徙瓶。
-
任務(wù)分析
首先我們找到Y(jié)elp香港餐廳的列表頁面毛雇,這個頁面是我們的起始頁面,對我們有用的信息為:餐廳列表和跳轉(zhuǎn)頁碼倍啥。
點擊進入餐廳的詳情頁面禾乘,可以看到基本信息和用戶評論,這里需要注意評論是區(qū)分語言的
Scrapy項目結(jié)構(gòu)
.
├── README.md
└── yelp
├── __init__.py
├── scrapy.cfg
└── yelp
├── __init__.py
├── items.py
├── middlewares.py
├── pipelines.py
├── settings.py
└── spiders
├── YelpSpider.py
└── __init__.py
這就是一個普通的Scrapy爬蟲的項目結(jié)構(gòu)虽缕,本文主要介紹如何實現(xiàn)斷點續(xù)爬始藕,所以如何獲取詳細字段內(nèi)容的方式可以直接查看源碼。
- 斷點續(xù)爬的實現(xiàn)
由于我們需要斷點續(xù)爬氮趋,那么就必須要在某一個時刻記錄當前的爬蟲狀態(tài)伍派,哪些頁面已經(jīng)爬過,哪些還沒有爬過剩胁。
我們將每一個需要爬取的頁面抽象為一個爬蟲任務(wù)诉植,從該頁面獲取數(shù)據(jù)完成則認為該任務(wù)完成。設(shè)計這個任務(wù)的數(shù)據(jù)結(jié)構(gòu):
class TaskBean(base):
__tablename__ = 'yelp_tasks'
id = Column(Integer, primary_key=True) # 任務(wù)ID
city = Column(String(256), nullable=False)
url = Column(String(1024), nullable=False) # 爬蟲任務(wù)的URL
is_finished = Column(Boolean, default=False) # 標記該頁面是否已經(jīng)爬過
parent_id = Column(Integer, default=-1) # 父任務(wù)的ID昵观,這樣所有任務(wù)形成一棵樹
type = Column(Integer) # 任務(wù)類型晾腔,1. 頁面列表任務(wù) 2. 餐廳詳情任務(wù) 3. 評論任務(wù)
def to_dict(self):
return {'task_id': self.id, 'city': self.city, 'url': self.url, 'is_finished': self.is_finished, 'type': self.type}
這個數(shù)據(jù)結(jié)構(gòu)中,我們定義了is_finished字段用來標記該任務(wù)是否已經(jīng)完成
is_finished = Column(Boolean, default=False) # 標記該頁面是否已經(jīng)爬過
并且定義了三種類型的任務(wù)
TASK_TYPE_LIST = 1 # 頁面列表任務(wù)
TASK_TYPE_RESTAURANT = 2 # 餐廳詳情任務(wù)
TASK_TYPE_REVIEW = 3 # 評論任務(wù)
OK,任務(wù)已經(jīng)定義完了,那怎么保存這個任務(wù)以及何時保存呢硫痰?
考慮到爬蟲任務(wù)隨時可能中斷,那么已爬取的數(shù)據(jù)可能隨之丟失剔应,我并沒有沒有用scrapy的pipeline和items來保存數(shù)據(jù)和任務(wù)進度,而是用了MySQL+sqlalchemy在同一個transaction中同時保存數(shù)據(jù)和任務(wù)進度语御。
下面的代碼以爬取餐廳列表為例
if task.type == TASK_TYPE_LIST: # Restaurant list page
# Get page url links
page_tasks = []
for page_url in response.selector.xpath('//*[@id="wrap"]/div[3]/div[2]/div[2]/div/div[1]/div[1]/div/div[1]/div/div[2]/div/div/a/@href').extract():
page_url = response.urljoin(page_url)
if page_url not in self.all_urls:
page_task = TaskBean()
page_task.city = city
page_task.url = page_url
page_task.type = TASK_TYPE_LIST
page_tasks.append(page_task)
self.all_urls.add(page_url)
# Get restaurant links
restaurant_tasks = []
for restaurant_section in response.selector.xpath('//*[@id="wrap"]/div[3]/div[2]/div[2]/div/div[1]/div[1]/div/ul/li/div/div/div/div/div[2]/div[1]'):
# name = restaurant_section.xpath('div[1]/div[1]/div[1]/h3/a/@title').extract_first()
if restaurant_section.xpath('div[1]/div[1]/div[1]/h3/span').extract():
continue
url = response.urljoin(restaurant_section.xpath('div[1]/div[1]/div[1]/h3/a/@href').extract_first())
if url not in self.all_urls:
restaurant_task = TaskBean()
restaurant_task.url = url
restaurant_task.city = city
restaurant_task.type = TASK_TYPE_RESTAURANT
restaurant_tasks.append(restaurant_task)
self.all_urls.add(url)
# 最后添加頁面任務(wù)峻贮、餐廳詳情頁任務(wù)并將當前任務(wù)置位已完成,這些需要在同一個transaction中完成
task.is_finished = True
session.add(task)
session.add_all(page_tasks)
session.add_all(restaurant_tasks)
session.commit()
- 隨機U-A反爬蟲設(shè)置
# Crawl responsibly by identifying yourself (and your website) on the user-agent
YELP_USER_AGENT = ["Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
"Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
"Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
"Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
"Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
"Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
"Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"]
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddleware.useragent.UserAgentMiddleware': None,
'dianping.middlewares.DianpingUserAgentMiddleware': 400,
}
class YelpUserAgentMiddleware(UserAgentMiddleware):
'''
設(shè)置User-Agent
'''
def __init__(self, user_agent):
self.user_agent = user_agent
@classmethod
def from_crawler(cls, crawler):
return cls(
user_agent=crawler.settings.get('YELP_USER_AGENT')
)
def process_request(self, request, spider):
agent = random.choice(self.user_agent)
request.headers['User-Agent'] = agent
- 完整代碼查看
從GitHub下載完整代碼