1.Scrapy框架
Scrapy是一個異步框架,效率比requests阻塞式編程效率要高慷荔。
2. 安裝
先下載twisted和pywin32
pip3 install scrapy
3.初次使用
- 新建項目
scrapy startproject dy2018
使用框架的好處就是我們不需要考慮任務(wù)調(diào)度問題汰寓,scrapy還有個特點就是會自動使用瀏覽器設(shè)置的代理吆寨,這個對于內(nèi)網(wǎng)使用非常有意義,還可以方便Fiddler獲取報文信息踩寇。
這里的拿http://www.dy2018.com 作為例子啄清,畢竟前面我們分析過。爬蟲需要繼承自scrapy.Spider俺孙,爬蟲初始鏈接放在start_urls中辣卒,parse函數(shù)作為頁面分析器來解析頁面數(shù)據(jù)和頁面鏈接。parse返回一個生成器睛榄,生成器生成的內(nèi)容只能是dict荣茫,request,none等场靴。
代碼如下:
import scrapy
from bs4 import BeautifulSoup
import re
class Dy2018Spider(scrapy.Spider):
name = "dy2018"
# start_urls = [
# 'http://quotes.toscrape.com/page/1/',
# 'http://quotes.toscrape.com/page/2/',
# ]
root = 'http://www.dy2018.com'
start_urls = ['http://www.dy2018.com/1/']
# for i in range(21):
# start_urls.append(root+'/'+str(i)+'/')
def parse(self, response):
#print(response.body)
self.logger.info(response.headers)
if b'Etag' not in response.headers:
self.logger.info('-----------------------------------------------------------')
self.logger.info(response.body)
self.logger.info(type(response.body))
url = self.geturl(response.body)
self.logger.info(url)
yield scrapy.Request(str(url), callback=self.parse)
else:
self.logger.info('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
ret = self.parsepage(response.body)
self.logger.info(ret)
# for url in ret['urls']:
# print(url)
# yield scrapy.Request(str(url), callback=self.parse)
for d in ret['data']:#不能返回一個list
yield d
def geturl(self,html):
soup = BeautifulSoup(html,'html5lib')
s = soup.find('script')
text = s.text
if text.startswith('window.location='):
path = self.root + eval(text[len('window.location='):-1])
return path
def parsepage(self,html):
soup = BeautifulSoup(html,'html5lib')
content = soup.find('div',attrs={'class':'co_content8'})
pages = content.find('div',attrs={'class':'x'})
urls = []
for option in pages.find_all('option'):
urls.append(self.root+option['value'])
pattern = re.compile(r'《(.+)》')
tbs = content.find_all('table')
data = []
for tb in tbs:
b = tb.find('b')
a1 = b.find_all('a')[1]
title = a1['title']
href = self.root + a1['href']
#title = pattern.findall(title)[0]
data.append({'href':href,'title':title})
self.logger.info(urls)
return {'data':data,'urls':urls}
- 運行方法
#要進入到dy2018這個工程目錄才能執(zhí)行下面的命令
scrapy crawl dy2018 --logfile 1.txt
- 調(diào)試的過程
(1)www.dy2018.com 使用了一些反扒技巧啡莉,前面我們分析過它會返回一個帶腳本的內(nèi)容來檢測是不是爬蟲在運行。前面使用Content-Length來區(qū)分正常頁面和爬蟲頁面旨剥,但是Content-Length在response.headers中卻找不到咧欣,所以這里使用Etag來檢測。當(dāng)然并不是說Content-Length就會被丟失轨帜,其實測試其它網(wǎng)站它是存在的魄咕。
(2)從代碼中我們可以看到'ETag'前綴是b,這代表字符串的類型是bytes蚌父。在scrapy的函數(shù)中起碼在scrapy.Request第一個參數(shù)是不能傳入bytes類型的哮兰,這里使用str把bytes類型轉(zhuǎn)換為str類型。response中的內(nèi)容也是bytes類型苟弛,在使用中要注意類型轉(zhuǎn)換喝滞。
(3)www.dy2018.com還有個反爬行為就是User-Agent,我估計是這樣膏秫,因為今天測試的時候發(fā)現(xiàn)反復(fù)會爬到反爬頁面右遭。我們可以在settings.py對這個進行設(shè)置。
#setting.py文件
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.8',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36',
}
(4)調(diào)試問題我這里使用的是log文件荔睹,要把調(diào)試信息輸入到文件中要使用self.logger.info函數(shù)狸演。