開始學習下scrapy這個爬蟲框架,安裝過程可以隨便google,這里不再贅述
scrapy文檔 這里面有個入門教程可以參考
今天示例網站用的是之前的天氣查詢。將它改成用scrapy來爬取
image.png
創建項目
- 首先必須創建一個新的Scrapy項目。 進入打算存儲代碼的目錄中,運行下列命令:
scrapy startproject scrapy_weather
然后就會生成一個空項目,進入其中使用tree
命令可以看到如下目錄樹:
│ scrapy.cfg
│
└─scrapy_weather
│ items.py
│ middlewares.py
│ pipelines.py
│ settings.py
│ __init__.py
│
├─spiders
│ __init__.py
-
scrapy.cfg
: 項目的配置文件 -
scrapy_weather/
: 該項目的python模塊。之后您將在此加入代碼。 -
scrapy_weather/items.py
: 項目中的item文件. -
scrapy_weather/pipelines.py
: 項目中的pipelines文件. -
scrapy_weather/settings.py
: 項目的設置文件. -
scrapy_weather/spiders/
: 放置spider代碼的目錄.
定義item
- 需要從
weather.com.cn
獲取到的數據對item進行建模:
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
編寫爬蟲
- 在
spiders
目錄下新建weather_spider.py
必須繼承scrapy.Spider
且有name
,start_urls
,parse()
三個屬性
name
會在運行的時候用到,必須唯一
以下是我這個爬蟲,也就是用bs4分析網頁,不多說了
import scrapy
from scrapy_weather.items import ScrapyWeatherItem
from bs4 import BeautifulSoup
class WeatherSoider(scrapy.Spider):
# name:用于區別Spider。該名字必須是唯一的
name = 'weather'
# 可選。包含了spider允許爬取的域名(domain)列表(list)。 當 OffsiteMiddleware 啟用時, 域名不在列表中的URL不會被跟進
allowed_domains = ['weather.com.cn']
# start_urls:包含了Spider在啟動時進行爬取的url列表。
# 因此,第一個被獲取到的頁面將是其中之一。后續的URL則從初始的URL獲取到的數據中提取
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的一個方法。被調用時,每個初始URL完成下載后生成的Response對象將會作為唯一的參數傳遞給該函數。
# 該方法負責解析返回的數據(responsedata),提取數據
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
處理爬取到的數據
上一步爬蟲的item
會返回到Pipeline
中,所以我們在這里處理數據即可,這一步也可以省略,只要在運行命令后加個-o weather.json
,這樣也可以將數據保存到這個json文件中
# spider中抓取的數據會返回到這里,我們可以在這里對數據進行保存到文件,數據庫等操作
import codecs
class ScrapyWeatherPipeline(object):
def __init__(self):
self.file = codecs.open('G:/python/weather.xml', 'w', encoding='utf-8') # 初始化一個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
中設置一些東西,比如robots.txt
具體我還沒仔細看
運行
- 進入項目目錄
scrapy crawl weather
這樣就會運行了
爬取到的item如下
image.png - 使用命令
scrapy crawl weather -o weather.json
會運行并將數據保存到這個文件中