1.Scrapy框架
Scrapy是一個(gè)異步框架,效率比requests阻塞式編程效率要高。
2. 安裝
先下載twisted和pywin32
pip3 install scrapy
3.初次使用
- 新建項(xiàng)目
scrapy startproject dy2018
使用框架的好處就是我們不需要考慮任務(wù)調(diào)度問題,scrapy還有個(gè)特點(diǎn)就是會(huì)自動(dòng)使用瀏覽器設(shè)置的代理,這個(gè)對(duì)于內(nèi)網(wǎng)使用非常有意義,還可以方便Fiddler獲取報(bào)文信息。
這里的拿http://www.dy2018.com 作為例子,畢竟前面我們分析過。爬蟲需要繼承自scrapy.Spider,爬蟲初始鏈接放在start_urls中,parse函數(shù)作為頁面分析器來解析頁面數(shù)據(jù)和頁面鏈接。parse返回一個(gè)生成器,生成器生成的內(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']:#不能返回一個(gè)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}
- 運(yùn)行方法
#要進(jìn)入到dy2018這個(gè)工程目錄才能執(zhí)行下面的命令
scrapy crawl dy2018 --logfile 1.txt
- 調(diào)試的過程
(1)www.dy2018.com 使用了一些反扒技巧,前面我們分析過它會(huì)返回一個(gè)帶腳本的內(nèi)容來檢測是不是爬蟲在運(yùn)行。前面使用Content-Length來區(qū)分正常頁面和爬蟲頁面,但是Content-Length在response.headers中卻找不到,所以這里使用Etag來檢測。當(dāng)然并不是說Content-Length就會(huì)被丟失,其實(shí)測試其它網(wǎng)站它是存在的。
(2)從代碼中我們可以看到'ETag'前綴是b,這代表字符串的類型是bytes。在scrapy的函數(shù)中起碼在scrapy.Request第一個(gè)參數(shù)是不能傳入bytes類型的,這里使用str把bytes類型轉(zhuǎn)換為str類型。response中的內(nèi)容也是bytes類型,在使用中要注意類型轉(zhuǎn)換。
(3)www.dy2018.com還有個(gè)反爬行為就是User-Agent,我估計(jì)是這樣,因?yàn)榻裉鞙y試的時(shí)候發(fā)現(xiàn)反復(fù)會(huì)爬到反爬頁面。我們可以在settings.py對(duì)這個(gè)進(jìn)行設(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ù)。