開(kāi)始學(xué)習(xí)下scrapy這個(gè)爬蟲(chóng)框架,安裝過(guò)程可以隨便google,這里不再贅述
scrapy文檔 這里面有個(gè)入門(mén)教程可以參考
今天示例網(wǎng)站用的是之前的天氣查詢。將它改成用scrapy來(lái)爬取

image.png
創(chuàng)建項(xiàng)目
- 首先必須創(chuàng)建一個(gè)新的Scrapy項(xiàng)目。 進(jìn)入打算存儲(chǔ)代碼的目錄中,運(yùn)行下列命令:
scrapy startproject scrapy_weather
然后就會(huì)生成一個(gè)空項(xiàng)目,進(jìn)入其中使用tree命令可以看到如下目錄樹(shù):
│ scrapy.cfg
│
└─scrapy_weather
│ items.py
│ middlewares.py
│ pipelines.py
│ settings.py
│ __init__.py
│
├─spiders
│ __init__.py
-
scrapy.cfg: 項(xiàng)目的配置文件 -
scrapy_weather/: 該項(xiàng)目的python模塊。之后您將在此加入代碼。 -
scrapy_weather/items.py: 項(xiàng)目中的item文件. -
scrapy_weather/pipelines.py: 項(xiàng)目中的pipelines文件. -
scrapy_weather/settings.py: 項(xiàng)目的設(shè)置文件. -
scrapy_weather/spiders/: 放置spider代碼的目錄.
定義item
- 需要從
weather.com.cn獲取到的數(shù)據(jù)對(duì)item進(jìn)行建模:
import scrapy
class ScrapyWeatherItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
date = scrapy.Field()
title = scrapy.Field()
tem = scrapy.Field()
win = scrapy.Field()
win_lv = scrapy.Field()
pass
編寫(xiě)爬蟲(chóng)
- 在
spiders目錄下新建weather_spider.py
必須繼承scrapy.Spider且有name,start_urls,parse()三個(gè)屬性
name會(huì)在運(yùn)行的時(shí)候用到,必須唯一
以下是我這個(gè)爬蟲(chóng),也就是用bs4分析網(wǎng)頁(yè),不多說(shuō)了
import scrapy
from scrapy_weather.items import ScrapyWeatherItem
from bs4 import BeautifulSoup
class WeatherSoider(scrapy.Spider):
# name:用于區(qū)別Spider。該名字必須是唯一的
name = 'weather'
# 可選。包含了spider允許爬取的域名(domain)列表(list)。 當(dāng) OffsiteMiddleware 啟用時(shí), 域名不在列表中的URL不會(huì)被跟進(jìn)
allowed_domains = ['weather.com.cn']
# start_urls:包含了Spider在啟動(dòng)時(shí)進(jìn)行爬取的url列表。
# 因此,第一個(gè)被獲取到的頁(yè)面將是其中之一。后續(xù)的URL則從初始的URL獲取到的數(shù)據(jù)中提取
start_urls = [
"http://www.weather.com.cn/weather/101010100.shtml",
"http://www.weather.com.cn/weather/101020100.shtml",
"http://www.weather.com.cn/weather/101210101.shtml",
]
#parse()是spider的一個(gè)方法。被調(diào)用時(shí),每個(gè)初始URL完成下載后生成的Response對(duì)象將會(huì)作為唯一的參數(shù)傳遞給該函數(shù)。
# 該方法負(fù)責(zé)解析返回的數(shù)據(jù)(responsedata),提取數(shù)據(jù)
def parse(self, response):
item = ScrapyWeatherItem()
html = response.body
soup = BeautifulSoup(html, 'html.parser')
data = soup.find("div", {'id': '7d'})
wea = {}
wea['date'] = data.find_all('h1')
wea['title'] = data.find_all('p',{'class': 'wea'} )
wea['tem'] = data.find_all('p', {'class': 'tem'})
wea['win'] = data.find_all('p', {'class': 'win'})
for w in wea:
item[w] = []
for o in wea.get(w):
if w == 'date':
item[w].append(o.get_text())
elif w == 'title':
item[w].append(o['title'])
elif w == 'win':
win1 = o.find('span')['title']
win2 = o.find('span').find_next()['title']
win_lv = o.i.get_text()
item[w].append('%s %s %s' % (win1, win2, win_lv))
elif w == 'tem':
high = o.find('span').get_text()
lower = o.find('i').get_text()
item[w].append('最高溫:%s,最低溫:%s' %(high, lower))
return item
處理爬取到的數(shù)據(jù)
上一步爬蟲(chóng)的item會(huì)返回到Pipeline中,所以我們?cè)谶@里處理數(shù)據(jù)即可,這一步也可以省略,只要在運(yùn)行命令后加個(gè)-o weather.json,這樣也可以將數(shù)據(jù)保存到這個(gè)json文件中
# spider中抓取的數(shù)據(jù)會(huì)返回到這里,我們可以在這里對(duì)數(shù)據(jù)進(jìn)行保存到文件,數(shù)據(jù)庫(kù)等操作
import codecs
class ScrapyWeatherPipeline(object):
def __init__(self):
self.file = codecs.open('G:/python/weather.xml', 'w', encoding='utf-8') # 初始化一個(gè)weather.xml的文件
def process_item(self, item, spider):
for i in range(0,7):
s = ''
for sub in item:
s += item[sub][i] + ' '
self.file.write(s+'\n')
if i == 6:
self.file.write('\n')
return item
最后可以在settings.py中設(shè)置一些東西,比如robots.txt具體我還沒(méi)仔細(xì)看
運(yùn)行
- 進(jìn)入項(xiàng)目目錄
scrapy crawl weather這樣就會(huì)運(yùn)行了
爬取到的item如下
image.png - 使用命令
scrapy crawl weather -o weather.json會(huì)運(yùn)行并將數(shù)據(jù)保存到這個(gè)文件中
