題記
上一篇爬的是www.dy2018.com泵额,其實(shí)只是爬了電影列表中的標(biāo)題和電影詳細(xì)頁鏈接而已,并沒有對爬電影的詳細(xì)頁面。今天要爬的網(wǎng)站是http://www.87g.com/ 躁愿,當(dāng)然我不想爬整個(gè)站叛本,那就爬爬這個(gè)網(wǎng)站中的美女吧。
1.目標(biāo)網(wǎng)站分析
http://www.87g.com/tupian/mnml.html 彤钟,這是目標(biāo)網(wǎng)址来候。
這個(gè)網(wǎng)站與dy2018不一樣的就是圖片列表是動(dòng)態(tài)加載的,頁面上沒有分頁功能逸雹。對于動(dòng)態(tài)加載問題應(yīng)該如何處理营搅,這是我們以前沒有碰到的。按F12打開開發(fā)者工具梆砸,點(diǎn)到Network頁面转质,向下滾動(dòng)鼠標(biāo)。
截圖里面產(chǎn)生了網(wǎng)絡(luò)請求辫樱,而且還返回了六張圖片峭拘。
#請求地址
http://www.87g.com/index.php?m=content&c=content_ajax&a=picture_page&siteid=1&catid=35&page=7&_=1483880663241
#返回?cái)?shù)據(jù)
{
1309: {id: "1309", content: "", readpoint: "0", groupids_view: "", paginationtype: "0", maxcharperpage: "0",…}
1310: {id: "1310", content: "", readpoint: "0", groupids_view: "", paginationtype: "0", maxcharperpage: "0",…}
1313: {id: "1313", content: "", readpoint: "0", groupids_view: "", paginationtype: "0", maxcharperpage: "0",…}
1314: {id: "1314", content: "", readpoint: "0", groupids_view: "", paginationtype: "0", maxcharperpage: "0",…}
1316: {id: "1316", content: "", readpoint: "0", groupids_view: "", paginationtype: "0", maxcharperpage: "0",…}
1317: {id: "1317", content: "", readpoint: "0", groupids_view: "", paginationtype: "0", maxcharperpage: "0",…}
}
可以分析一下請求這個(gè)鏈接,是不是看到一個(gè)page參數(shù)狮暑,如果修改這個(gè)page值是不是可以返回其它數(shù)據(jù)呢!實(shí)踐證明確實(shí)是這樣的鸡挠。
美女列表分析完了,這時(shí)候隨便點(diǎn)一個(gè)圖片就能進(jìn)入美女的美照詳細(xì)頁面搬男,這個(gè)頁面有很多圖片拣展,這些圖片就是要下載的圖片。
2.爬蟲編寫
- json解碼
根據(jù)上面的分析缔逛,我并不需要加載http://www.87g.com/tupian/mnml.html 备埃,直接訪問上面的鏈接就可以獲得所需的數(shù)據(jù)。注意response.body是bytes類型褐奴,所以需要轉(zhuǎn)化為utf-8按脚。json中的key沒有實(shí)際意義,所以在代碼中就直接忽略了敦冬。
#parse函數(shù)
data = json.loads(response.body.decode('utf-8'))
for v in data.values():
url = v['url']
url = response.urljoin(url)
yield scrapy.Request(url, callback=self.parsepage)
#parsepage用來分析詳細(xì)頁面
- xpath
上個(gè)例子解析頁面使用的是BeautifulSoup辅搬,很簡單也很好用,這里使用的是xpath脖旱。在詳細(xì)頁中按F12堪遂,打開Elements標(biāo)簽。
#這個(gè)是復(fù)制出來的xpath
//*[@id="mkPic"]/ul/li[1]/a/img
這時(shí)候我們要驗(yàn)證xpath是否能獲取我想要的數(shù)據(jù)(圖片鏈接地址)萌庆。
scrapy有個(gè)shell命令溶褪,特別好用。
Microsoft Windows [版本 6.1.7601]
版權(quán)所有 (c) 2009 Microsoft Corporation践险。保留所有權(quán)利猿妈。
C:\Users\Administrator>scrapy shell "http://www.87g.com/tupian/1356.html"
2017-01-08 21:34:07 [scrapy.utils.log] INFO: Scrapy 1.3.0 started (bot: scrapybot)
2017-01-08 21:34:07 [scrapy.utils.log] INFO: Overridden settings: {'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDupeFilte
r', 'LOGSTATS_INTERVAL': 0}
2017-01-08 21:34:08 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.telnet.TelnetConsole',
'scrapy.extensions.corestats.CoreStats']
2017-01-08 21:34:08 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
'scrapy.downloadermiddlewares.retry.RetryMiddleware',
'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
'scrapy.downloadermiddlewares.stats.DownloaderStats']
2017-01-08 21:34:08 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
'scrapy.spidermiddlewares.referer.RefererMiddleware',
'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
'scrapy.spidermiddlewares.depth.DepthMiddleware']
2017-01-08 21:34:08 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2017-01-08 21:34:08 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2017-01-08 21:34:08 [scrapy.core.engine] INFO: Spider opened
2017-01-08 21:34:08 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://www.87g.com/tupian/1356.html> (referer: None)
[s] Available Scrapy objects:
[s] scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s] crawler <scrapy.crawler.Crawler object at 0x00000000007E7358>
[s] item {}
[s] request <GET http://www.87g.com/tupian/1356.html>
[s] response <200 http://www.87g.com/tupian/1356.html>
[s] settings <scrapy.settings.Settings object at 0x0000000004AB0CF8>
[s] spider <DefaultSpider 'default' at 0x4ca69e8>
[s] Useful shortcuts:
[s] fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)
[s] fetch(req) Fetch a scrapy.Request and update local objects
[s] shelp() Shell help (print this help)
[s] view(response) View response in a browser
>>>
上面顯示了很多內(nèi)容吹菱,其實(shí)就是個(gè)python命令行環(huán)境,只是內(nèi)置了一些scrapy對象于游。
>>> response.xpath('//*[@id="mkPic"]/ul/li[1]/a/img')
[<Selector xpath='//*[@id="mkPic"]/ul/li[1]/a/img' data='<img src="http://pic.87g.com/upload/2016'>]
把復(fù)制的xpath放進(jìn)去確實(shí)能獲取到img這個(gè)標(biāo)簽毁葱,可是出來的是Selector,那就再加個(gè)extract函數(shù)調(diào)用吧贰剥!
>>> response.xpath('//*[@id="mkPic"]/ul/li[1]/a/img').extract()
['![](http://upload-images.jianshu.io/upload_images/3797605-12b90ecdc0f8f05a.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)']
這里我簡略的談一下xpath語法倾剿,@attr可以獲取屬性,一個(gè)/可以理解為層級結(jié)構(gòu)蚌成,//代表根路徑前痘,*代表任何元素標(biāo)簽。對這個(gè)xpath修改一下担忧,達(dá)到我的要求芹缔,獲取li下面所有的img,還有進(jìn)一步獲取scr的屬性值瓶盛。
>>> response.xpath('//*[@id="mkPic"]/ul/li/a/img').extract()
['![](http://upload-images.jianshu.io/upload_images/3797605-12b90ecdc0f8f05a.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)', '<img src="http://pic.87g.com/upload/20
16/1224/20161224012001638.jpg" alt="">', '![](http://upload-images.jianshu.io/upload_images/3797605-fba36be14ad2c82b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)',
'![](http://upload-images.jianshu.io/upload_images/3797605-9ad72bf1a187530e.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)', '<img src="http://pic.87g.com/upload/20
16/1224/20161224012003259.jpg" alt="">', '![](http://upload-images.jianshu.io/upload_images/3797605-c429052a110b7a37.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)',
'![](http://upload-images.jianshu.io/upload_images/3797605-6aa1f2fc33e11ac5.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)', '<img src="http://pic.87g.com/upload/20
16/1224/20161224012004123.jpg" alt="">', '![](http://upload-images.jianshu.io/upload_images/3797605-4cb6d7933fd824a0.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)',
'![](http://upload-images.jianshu.io/upload_images/3797605-a0557bb670f0698a.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)', '<img src="http://pic.87g.com/upload/20
16/1224/20161224012006618.jpg" alt="">', '![](http://upload-images.jianshu.io/upload_images/3797605-33d638d1bbdd88f6.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)']
我把初始的xpath中l(wèi)i后面的序號去掉了最欠,還在后面加了'/@src',就這兩個(gè)區(qū)別就獲取了所有圖片的地址惩猫。不得不說xpath比BeautifulSoup還簡單芝硬,我甚至并不懂多少xpath語法。
- 詳細(xì)頁編碼
def parsepage(self, response):
image_urls= response.xpath('//*[@id="mkPic"]/ul/li/a/img/@src').extract()
return {'image_urls':image_urls}
上面的代碼其實(shí)很簡單轧房,但是有沒有注意到一個(gè)問題拌阴,分析json所在的函數(shù)是parse,而處理詳細(xì)頁卻在parsepage這個(gè)函數(shù)奶镶。分而治之的好處就是我不需要判斷該如何處理當(dāng)前頁面內(nèi)容迟赃,因?yàn)槊總€(gè)函數(shù)處理的頁面已經(jīng)固定好了。
- 圖片下載
spider在完成頁面的下載和分析之后接著會(huì)進(jìn)入pipeline厂镇,parsepage函數(shù)返回一個(gè)圖片鏈接列表給pipeline纤壁。
#pipelines.py
import requests
import os
class ImageDownloadPipeline(object):
def process_item(self, item, spider):
if 'image_urls' in item:#如何‘圖片地址’在項(xiàng)目中
images = []#定義圖片空集
#dir_path = ''%s/%s' % (settings.IMAGES_STORE, spider.name)'
dir_path = 'D:/images'#圖片保存路徑
if not os.path.exists(dir_path):
os.makedirs(dir_path)#創(chuàng)建文件夾
for image_url in item['image_urls']:
us = image_url.split('/')[3:]#獲取路徑地址,實(shí)際這個(gè)方法不太通用
#使用image_url[image_url.rfind('/')+1:]會(huì)是一個(gè)更通用的辦法
image_file_name = '_'.join(us)
file_path = '%s/%s' % (dir_path, image_file_name)
images.append(file_path)
if os.path.exists(file_path):
continue
with open(file_path, 'wb') as handle:
response = requests.get(image_url, stream=True)
for block in response.iter_content(1024):
if not block:
break
handle.write(block)
item['images'] = images
return item
這里使用requests下載圖片捺信,requests不是異步庫因此會(huì)影響速度酌媒。在完成了這個(gè)類之后,還要去設(shè)置才能工作残黑。
#settings.py
ITEM_PIPELINES = {
# 'myproject.pipelines.MongoPipeline': 300,
'myproject.pipelines.ImageDownloadPipeline': 300, #這個(gè)用來在mm97這個(gè)爬蟲下載圖片
# 'scrapy.pipelines.images.ImagesPipeline': 1,#系統(tǒng)自帶的下載圖片
}
IMAGES_STORE = 'D:/meizitu'
當(dāng)然也可以是用系統(tǒng)自帶的圖片下載pipeline,還可以在settings.py設(shè)置保存路徑(IMAGE_STORE)斋否。
3.思考
(1)一開始的時(shí)候肯定不會(huì)想到直接獲取json來獲取頁面內(nèi)容梨水,直接分析頁面也是可以獲取內(nèi)容的,但是動(dòng)態(tài)加載茵臭,使得直接分析存在數(shù)據(jù)不全的問題疫诽。還有程序中沒有考慮到該獲取多少頁的問題,代碼中我設(shè)置的是100頁,實(shí)際上確實(shí)在一百頁左右奇徒,這個(gè)手動(dòng)驗(yàn)證的雏亚。要是幾千頁上萬頁那應(yīng)該如何獲取邊界問題呢,我想到一個(gè)二分法的問題摩钙。我假設(shè)初始值設(shè)置為100罢低,獲取第100頁,如果有內(nèi)容胖笛,那么就獲取第200頁网持,要是沒有內(nèi)容,以一個(gè)值就是150頁长踊。功舀。。
init_page = 100
end = init_page
start = 1
while True:
if get(end) is None:
end = (start+end)/2
else:
start = end
end = 2*end
if start == end:
break
(2)這里再說說其它一個(gè)例子身弊,www.meizitu.com這個(gè)網(wǎng)站有反爬蟲機(jī)制辟汰,實(shí)際就是會(huì)封ip,這個(gè)后面會(huì)繼續(xù)推進(jìn)如何解決這個(gè)問題阱佛!