飾模式使用對(duì)象組合的方式動(dòng)態(tài)改變或增加對(duì)象行為。Go語言借助于匿名組合和非入侵式接口可以很方便實(shí)現(xiàn)裝飾模式。使用匿名組合,在裝飾器中不必顯式定義轉(zhuǎn)調(diào)原對(duì)象方法。
在這里插入圖片描述
裝飾器模式主要解決繼承關(guān)系過于復(fù)雜的問題,通過組合來代替繼承,給原始類添加增強(qiáng)功能,這也是判斷裝飾器的一個(gè)重要依據(jù),除此之外,裝飾器還有一個(gè)特點(diǎn),可以對(duì)原始類嵌套使用多個(gè)裝飾器,為了滿足這樣的需求,在設(shè)計(jì)的時(shí)候,裝飾器類需要跟原始繼承同步的抽象類或者接口。
Java IO 通過4個(gè)基類,擴(kuò)展出很多子類, 具體如下:
裝飾器模式相對(duì)于簡(jiǎn)單的組合關(guān)系,有如下特殊點(diǎn):
package decorator
type Component interface {
Calc() int
}
type ConcreteComponent struct{}
func (*ConcreteComponent) Calc() int {
return 0
}
type MulDecorator struct {
Component
num int
}
func WarpMulDecorator(c Component, num int) Component {
return &MulDecorator{
Component: c,
num: num,
}
}
func (d *MulDecorator) Calc() int {
return d.Component.Calc() * d.num
}
type AddDecorator struct {
Component
num int
}
func WarpAddDecorator(c Component, num int) Component {
return &AddDecorator{
Component: c,
num: num,
}
}
func (d *AddDecorator) Calc() int {
return d.Component.Calc() + d.num
}
測(cè)試用例
package decorator
import (
"fmt"
"testing"
)
func TestExampleDecorator(t *testing.T) {
var c Component = &ConcreteComponent{}
c = WarpAddDecorator(c, 10)
c = WarpMulDecorator(c, 8)
res := c.Calc()
fmt.Printf("res %d\n", res)
// Output:
// res 80
}
運(yùn)行結(jié)果
=== RUN TestExampleDecorator
res 80
--- PASS: TestExampleDecorator (0.00s)
PASS
在這里插入圖片描述
言:
LDAP輕量目錄訪問協(xié)議為用戶管理提供了統(tǒng)一認(rèn)證服務(wù),解決了長(zhǎng)期存在的多套用戶認(rèn)證系統(tǒng)孤立、繁雜、難以維護(hù)的問題。具有簡(jiǎn)捷、高效、易用的特性,是用戶認(rèn)證管理的不二選擇。
一、簡(jiǎn)介
LDAP(Lightweight Directory Access Protocol)是基于X.500標(biāo)準(zhǔn)的輕量目錄訪問協(xié)議。它比X.500具有更快的查詢速度和更低的資源消耗,精簡(jiǎn)靈活,支持TCP/IP協(xié)議。LDAP為用戶管理提供了統(tǒng)一認(rèn)證服務(wù),解決了辦公環(huán)境中多套用戶認(rèn)證和項(xiàng)目管理系統(tǒng)相互獨(dú)立分散的難題。
OpenLDAP 是LDAP的開源實(shí)現(xiàn),OpenLDAP目錄中的信息是按照樹形結(jié)構(gòu)進(jìn)行組織的,具體信息存儲(chǔ)在條目(entry)中,條目是LDAP的基本元素,也是識(shí)別名(DN)的屬性集合,DN 具有全局唯一性,用于準(zhǔn)確地引用條目,每個(gè)條目屬性又包含類型(type)和值(value)。整體架構(gòu)如圖所示:
二、快速安裝
系統(tǒng)環(huán)境:CentOS7.3
主機(jī)名:openldap
系統(tǒng)IP:172.16.201.6
管理賬戶信息:dn:cn=Manager,dc=mydomain,dc=com
部署時(shí),可根據(jù)實(shí)際需求更改以上信息。
2.1.環(huán)境準(zhǔn)備
OpenLDAP正式部署前,首先對(duì)linux系統(tǒng)環(huán)境進(jìn)行如下準(zhǔn)備配置,以滿足OpenLDAP安裝運(yùn)行需求。
1.設(shè)置主機(jī)名:
hostnamectl set-hostname openldap
主機(jī)名可自行設(shè)置成任意名字,只需將openldap設(shè)置為更改的主機(jī)名即可。
2.關(guān)閉防火墻和selinux
systemctl stop firewalld systemctl disable firewalld sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
3.配置epel源,配置完成后重啟服務(wù)器,以使相關(guān)配置生效
yum install epel-release -y reboot
2.2.OpenLDAP安裝
1.安裝ldap相關(guān)組件
yum install openldap openldap-servers openldap-clients -y cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG
2.啟動(dòng)ldap服務(wù)
systemctl start slapd systemctl enable slapd systemctl status slapd
slapd即ldap的服務(wù)名稱
3.設(shè)置ldap管理員用戶密碼
slappasswd -s 111111 {SSHA}AjIAg98NFvRRlhoBOvsfVqMeAGZwi5O9
本次設(shè)置密碼為111111,若需要其他密碼直接更改該值即可。記錄執(zhí)行結(jié)果的返回值{SSHA}AjIAg98NFvRRlhoBOvsfVqMeAGZwi5O9,并將該值寫入到后邊生成的rootpwd.ldif文件中。
4.創(chuàng)建管理員用戶配置文件rootpwd.ldif
cat <<EOF>rootpwd.ldif dn: olcDatabase={0}config,cn=config changetype: modify add: olcRootPW olcRootPW: {SSHA}AjIAg98NFvRRlhoBOvsfVqMeAGZwi5O9 EOF
相關(guān)參數(shù)說明:
olcRootPW參數(shù)值為slappasswd命令的結(jié)果輸出。
olcRootPW: {SSHA}AjIAg98NFvRRlhoBOvsfVqMeAGZwi5O9指定了屬性值。
ldif文件是LDAP中數(shù)據(jù)交換的文件格式。文件內(nèi)容采用的是key-value形式。注意value后面不能有空格。
olc(OnlineConfiguration)表示寫入LDAP后立即生效。
changetype: modify表示修改entry,此外changetype的值也可以是add,delete等。
add: olcRootPW表示對(duì)這個(gè)entry新增olcRootPW的屬性。
5.導(dǎo)入rootpwd.ldif信息
ldapadd -Y EXTERNAL -H ldapi:/// -f rootpwd.ldif
6.導(dǎo)入schema
schema包含支持特殊場(chǎng)景的相關(guān)屬性,可選擇性導(dǎo)入或全部導(dǎo)入
ls /etc/openldap/schema/*.ldif | while read i; do ldapadd -Y EXTERNAL -H ldapi:/// -f $i; done
7.設(shè)置默認(rèn)域
slappasswd -s 111111 {SSHA}7AA7V1xy++LVZcUbBWYYM9/81wfODiIK
本次設(shè)置密碼為111111,若需要其他密碼直接更改該值即可。記錄執(zhí)行結(jié)果的
返回值{SSHA}7AA7V1xy++LVZcUbBWYYM9/81wfODiIK
8.新建默認(rèn)域配置文件
vi domain.ldif dn: olcDatabase={1}monitor,cn=config changetype: modify replace: olcAccess olcAccess: {0}to * by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" read by dn.base="cn=Manager,dc=mydomain,dc=com" read by * none dn: olcDatabase={2}hdb,cn=config changetype: modify replace: olcSuffix olcSuffix: dc=mydomain,dc=com dn: olcDatabase={2}hdb,cn=config changetype: modify replace: olcRootDN olcRootDN: cn=Manager,dc=mydomain,dc=com dn: olcDatabase={2}hdb,cn=config changetype: modify add: olcRootPW olcRootPW: {SSHA}7AA7V1xy++LVZcUbBWYYM9/81wfODiIK dn: olcDatabase={2}hdb,cn=config changetype: modifyadd: olcAccess olcAccess: {0}to attrs=userPassword,shadowLastChange by dn="cn=Manager,dc=mydomain,dc=com" write by anonymous auth by self write by * none olcAccess: {1}to dn.base="" by * read olcAccess: {2}to * by dn="cn=Manager,dc=mydomain,dc=com" write by * read
設(shè)置 olcRootPW參數(shù)值為slappwd命令的返回結(jié)果:{SSHA}7AA7V1xy++LVZcUbBWYYM9/81wfODiIK
9.寫入信息
ldapmodify -Y EXTERNAL -H ldapi:/// -f domain.ldif
10.添加基本信息
cat <<EOF> basedomain.ldif dn: dc=mydomain,dc=com objectClass: top objectClass: dc Objectobjectclass: organization o: mydomain com dc: mydomain dn: cn=Manager,dc=mydomain,dc=com objectClass: organizationalRole cn: Manager description: Directory Manager dn: ou=People,dc=mydomain,dc=com objectClass: organizationalUnit ou: People dn: ou=Group,dc=mydomain,dc=com objectClass: organizationalUnit ou: Group EOF
11.寫入信息
ldapadd -x -D cn=Manager,dc=mydomain,dc=com -W -f basedomain.ldif
12.查看信息
ldapsearch -LLL -W -x -D "cn=Manager,dc=mydomain,dc=com" -H ldap://localhost -b"dc=mydomain,dc=com"
使用如上命令進(jìn)行查看時(shí),輸入訪問密碼為:111111.能夠查看到相關(guān)返回結(jié)果為如下內(nèi)容,說明OpenLDAP配置成功。可進(jìn)行相關(guān)管理和使用。
[root@openldap ~]# ldapadd -x -D cn=Manager,dc=mydomain,dc=com -W -f basedomain.ldif Enter LDAP Password: adding new entry "dc=mydomain,dc=com" adding new entry "cn=Manager,dc=mydomain,dc=com" adding new entry "ou=People,dc=mydomain,dc=com" adding new entry "ou=Group,dc=mydomain,dc=com"
三、OpenLDAP管理工具
為簡(jiǎn)化OpenLDAP使用,提高工作效率,OpenLDAP支持多種管理工具,較常用的有如下兩款ldapadmin工具,可選擇任意一種。
工具一:
1.可在windows電腦上下載管理工具:
http://www.ldapadmin.org/download/ldapadmin.html
2.下載完成后,解壓該文件,直接雙擊運(yùn)行,輸入LDAP訪問信息。
Host值為OpenLDAP節(jié)點(diǎn)ip地址:172.16.201.6.
Base值為:dc=mydomain,dc=com
Username值為:cn=Manager,dc=mydomain,dc=com
Password值為:111111.
其余參數(shù)為默認(rèn)值。填寫完成后可點(diǎn)擊 "Test connection" 以測(cè)試是否能夠正常連接。
3.連接成功后可看到OpenLDAP相關(guān)信息
之后可直接創(chuàng)建用戶、組,或進(jìn)行增、刪、改操作。
工具二:
1.在OpenLDAP運(yùn)行節(jié)點(diǎn)安裝ldapadmin工具包
yum install -y httpd php php-mbstring php-pear phpldapadmin
2.修改/etc/httpd/httpd.conf配置文件
[root@www ~]# vi /etc/httpd/conf/httpd.conf # line 86: 修改admin郵箱地址 ServerAdmin root@openldap.mydomain.world # line 95: 修改主機(jī)域名 ServerName www.mydomain.com:80 # line 152: 修改成如下內(nèi)容: AllowOverride All # line 165: 添加可訪問目錄名的文件名稱 DirectoryIndex index.html index.cgi index.php # 在文件末尾增加如下兩部分內(nèi)容# server's response header ServerTokens Prod # keepalive is ON KeepAlive On
3.啟動(dòng)Apache服務(wù)并設(shè)置開機(jī)自啟動(dòng)
systemctl start httpd systemctl enable httpd
4.編輯/etc/phpldapadmin/config.php文件,按如下內(nèi)容修改:
vi /etc/phpldapadmin/config.php #注釋掉398行,并取消397行的注釋,修改后內(nèi)容如下: $servers->setValue('login','attr','dn'); // $servers->setValue('login','attr','uid');
5.編輯/etc/httpd/conf.d/phpldapadmin.conf,在第12行加入Require all granted以允許所有IP訪問,被更改部分內(nèi)容如下:
<Directory/usr/share/phpldapadmin/htdocs> <IfModule mod_authz_core.c> # Apache 2.4 Require local Require all granted </IfModule>
6.重啟Apache服務(wù)使配置生效
systemctl restart httpd
7.在瀏覽器輸入OpenLDAP訪問WEB地址:http://172.16.201.6/ldapadmin/
輸入登錄用戶名:cn=Manager,dc=mydomain,dc=com和密碼:111111
8.通過認(rèn)證后,可直接創(chuàng)建用戶、組,進(jìn)行增、刪、改操作。
crapy,Python開發(fā)的一個(gè)快速,高層次的屏幕抓取和web抓取框架,用于抓取web站點(diǎn)并從頁面中提取結(jié)構(gòu)化的數(shù)據(jù)。Scrapy用途廣泛,可以用于數(shù)據(jù)挖掘、監(jiān)測(cè)和自動(dòng)化測(cè)試。Scrapy吸引人的地方在于它是一個(gè)框架,任何人都可以根據(jù)需求方便的修改。它也提供了多種類型爬蟲的基類,如BaseSpider、sitemap爬蟲等,最新版本又提供了web2.0爬蟲的支持。Scratch,是抓取的意思,這個(gè)Python的爬蟲框架叫Scrapy,大概也是這個(gè)意思吧,就叫它:小刮刮吧。Scrapy 使用了 Twisted異步網(wǎng)絡(luò)庫來處理網(wǎng)絡(luò)通訊。整體架構(gòu)大致如下
Scrapy主要包括了以下組件:
引擎(Scrapy)
用來處理整個(gè)系統(tǒng)的數(shù)據(jù)流處理, 觸發(fā)事務(wù)(框架核心)
調(diào)度器(Scheduler)
用來接受引擎發(fā)過來的請(qǐng)求, 壓入隊(duì)列中, 并在引擎再次請(qǐng)求的時(shí)候返回. 可以想像成一個(gè)URL(抓取網(wǎng)頁的網(wǎng)址或者說是鏈接)的優(yōu)先隊(duì)列, 由它來決定下一個(gè)要抓取的網(wǎng)址是什么, 同時(shí)去除重復(fù)的網(wǎng)址
下載器(Downloader)
用于下載網(wǎng)頁內(nèi)容, 并將網(wǎng)頁內(nèi)容返回給蜘蛛(Scrapy下載器是建立在twisted這個(gè)高效的異步模型上的)
爬蟲(Spiders)
爬蟲是主要干活的, 用于從特定的網(wǎng)頁中提取自己需要的信息, 即所謂的實(shí)體(Item)。用戶也可以從中提取出鏈接,讓Scrapy繼續(xù)抓取下一個(gè)頁面
項(xiàng)目管道(Pipeline)
負(fù)責(zé)處理爬蟲從網(wǎng)頁中抽取的實(shí)體,主要的功能是持久化實(shí)體、驗(yàn)證實(shí)體的有效性、清除不需要的信息。當(dāng)頁面被爬蟲解析后,將被發(fā)送到項(xiàng)目管道,并經(jīng)過幾個(gè)特定的次序處理數(shù)據(jù)。
下載器中間件(Downloader Middlewares)
位于Scrapy引擎和下載器之間的框架,主要是處理Scrapy引擎與下載器之間的請(qǐng)求及響應(yīng)。
爬蟲中間件(Spider Middlewares)
介于Scrapy引擎和爬蟲之間的框架,主要工作是處理蜘蛛的響應(yīng)輸入和請(qǐng)求輸出。
調(diào)度中間件(Scheduler Middewares)
介于Scrapy引擎和調(diào)度之間的中間件,從Scrapy引擎發(fā)送到調(diào)度的請(qǐng)求和響應(yīng)。
Scrapy運(yùn)行流程大概如下:
引擎從調(diào)度器中取出一個(gè)鏈接(URL)用于接下來的抓取
引擎把URL封裝成一個(gè)請(qǐng)求(Request)傳給下載器
下載器把資源下載下來,并封裝成應(yīng)答包(Response)
爬蟲解析Response
解析出實(shí)體(Item),則交給實(shí)體管道進(jìn)行進(jìn)一步的處理
解析出的是鏈接(URL),則把URL交給調(diào)度器等待抓取
一、安裝
因?yàn)閜ython3并不能完全支持Scrapy,因此為了完美運(yùn)行Scrapy,我們使用python2.7來編寫和運(yùn)行Scrapy。
1 | pip install Scrapy |
注:windows平臺(tái)需要依賴pywin32,請(qǐng)根據(jù)自己系統(tǒng)32/64位選擇下載安裝,https://sourceforge.net/projects/pywin32/
其它可能依賴的安裝包:lxml-3.6.4-cp27-cp27m-win_amd64.whl,VCForPython27.msi百度下載即可
二、基本使用
1、創(chuàng)建項(xiàng)目
運(yùn)行命令:
1 | scrapy startproject p1(your_project_name) |
2.自動(dòng)創(chuàng)建目錄的結(jié)果:
文件說明:
scrapy.cfg 項(xiàng)目的配置信息,主要為Scrapy命令行工具提供一個(gè)基礎(chǔ)的配置信息。(真正爬蟲相關(guān)的配置信息在settings.py文件中)
items.py 設(shè)置數(shù)據(jù)存儲(chǔ)模板,用于結(jié)構(gòu)化數(shù)據(jù),如:Django的Model
pipelines 數(shù)據(jù)處理行為,如:一般結(jié)構(gòu)化的數(shù)據(jù)持久化
settings.py 配置文件,如:遞歸的層數(shù)、并發(fā)數(shù),延遲下載等
spiders 爬蟲目錄,如:創(chuàng)建文件,編寫爬蟲規(guī)則
注意:一般創(chuàng)建爬蟲文件時(shí),以網(wǎng)站域名命名
3、編寫爬蟲
在spiders目錄中新建 xiaohuar_spider.py 文件
示例代碼:
12345678910111213141516171819 | #!/usr/bin/env python# -*- coding:utf-8 -*-import scrapy class XiaoHuarSpider(scrapy.spiders.Spider):name="xiaohuar"allowed_domains=["xiaohuar.com"]start_urls=["http://www.xiaohuar.com/hua/",] def parse(self, response):# print(response, type(response))# from scrapy.http.response.html import HtmlResponse# print(response.body_as_unicode()) current_url=response.url #爬取時(shí)請(qǐng)求的urlbody=response.body#返回的htmlunicode_body=response.body_as_unicode()#返回的html unicode編碼 |
備注:
1.爬蟲文件需要定義一個(gè)類,并繼承scrapy.spiders.Spider
2.必須定義name,即爬蟲名,如果沒有name,會(huì)報(bào)錯(cuò)。因?yàn)樵创a中是這樣定義的:
3.編寫函數(shù)parse,這里需要注意的是,該函數(shù)名不能改變,因?yàn)镾crapy源碼中默認(rèn)callback函數(shù)的函數(shù)名就是parse;
4.定義需要爬取的url,放在列表中,因?yàn)榭梢耘廊《鄠€(gè)url,Scrapy源碼是一個(gè)For循環(huán),從上到下爬取這些url,使用生成器迭代將url發(fā)送給下載器下載url的html。源碼截圖:
4、運(yùn)行
進(jìn)入p1目錄,運(yùn)行命令
1 | scrapy crawl xiaohau --nolog |
格式:scrapy crawl+爬蟲名 –nolog即不顯示日志
5.scrapy查詢語法:
當(dāng)我們爬取大量的網(wǎng)頁,如果自己寫正則匹配,會(huì)很麻煩,也很浪費(fèi)時(shí)間,令人欣慰的是,scrapy內(nèi)部支持更簡(jiǎn)單的查詢語法,幫助我們?nèi)tml中查詢我們需要的標(biāo)簽和標(biāo)簽內(nèi)容以及標(biāo)簽屬性。下面逐一進(jìn)行介紹:
查詢子子孫孫中的某個(gè)標(biāo)簽(以div標(biāo)簽為例)://div
查詢兒子中的某個(gè)標(biāo)簽(以div標(biāo)簽為例):/div
查詢標(biāo)簽中帶有某個(gè)class屬性的標(biāo)簽://div[@class=’c1′]即子子孫孫中標(biāo)簽是div且class=‘c1’的標(biāo)簽
查詢標(biāo)簽中帶有某個(gè)class=‘c1’并且自定義屬性name=‘a(chǎn)lex’的標(biāo)簽://div[@class=’c1′][@name=’alex’]
查詢某個(gè)標(biāo)簽的文本內(nèi)容://div/span/text() 即查詢子子孫孫中div下面的span標(biāo)簽中的文本內(nèi)容
查詢某個(gè)屬性的值(例如查詢a標(biāo)簽的href屬性)://a/@href
示例代碼:
12345678910111213141516171819 | def parse(self, response):# 分析頁面# 找到頁面中符合規(guī)則的內(nèi)容(校花圖片),保存# 找到所有的a標(biāo)簽,再訪問其他a標(biāo)簽,一層一層的搞下去 hxs=HtmlXPathSelector(response)#創(chuàng)建查詢對(duì)象 # 如果url是 http://www.xiaohuar.com/list-1-\d+.htmlif re.match('http://www.xiaohuar.com/list-1-\d+.html', response.url): #如果url能夠匹配到需要爬取的url,即本站urlitems=hxs.select('//div[@class="item_list infinite_scroll"]/div') #select中填寫查詢目標(biāo),按scrapy查詢語法書寫for i in range(len(items)):src=hxs.select('//div[@class="item_list infinite_scroll"]/div[%d]//div[@class="img"]/a/img/@src' % i).extract()#查詢所有img標(biāo)簽的src屬性,即獲取校花圖片地址name=hxs.select('//div[@class="item_list infinite_scroll"]/div[%d]//div[@class="img"]/span/text()' % i).extract() #獲取span的文本內(nèi)容,即校花姓名school=hxs.select('//div[@class="item_list infinite_scroll"]/div[%d]//div[@class="img"]/div[@class="btns"]/a/text()' % i).extract() #校花學(xué)校if src:ab_src="http://www.xiaohuar.com" + src[0]#相對(duì)路徑拼接file_name="%s_%s.jpg" % (school[0].encode('utf-8'), name[0].encode('utf-8')) #文件名,因?yàn)閜ython27默認(rèn)編碼格式是unicode編碼,因此我們需要編碼成utf-8file_path=os.path.join("/Users/wupeiqi/PycharmProjects/beauty/pic", file_name)urllib.urlretrieve(ab_src, file_path) |
注:urllib.urlretrieve(ab_src, file_path) ,接收文件路徑和需要保存的路徑,會(huì)自動(dòng)去文件路徑下載并保存到我們指定的本地路徑。
5.遞歸爬取網(wǎng)頁
上述代碼僅僅實(shí)現(xiàn)了一個(gè)url的爬取,如果該url的爬取的內(nèi)容中包含了其他url,而我們也想對(duì)其進(jìn)行爬取,那么如何實(shí)現(xiàn)遞歸爬取網(wǎng)頁呢?
示例代碼:
12345 | # 獲取所有的url,繼續(xù)訪問,并在其中尋找相同的urlall_urls=hxs.select('//a/@href').extract()for url in all_urls:if url.startswith('http://www.xiaohuar.com/list-1-'):yield Request(url, callback=self.parse) |
即通過yield生成器向每一個(gè)url發(fā)送request請(qǐng)求,并執(zhí)行返回函數(shù)parse,從而遞歸獲取校花圖片和校花姓名學(xué)校等信息。
注:可以修改settings.py 中的配置文件,以此來指定“遞歸”的層數(shù),如: DEPTH_LIMIT=1
6.scrapy查詢語法中的正則:
123456789101112131415161718 | from scrapy.selector import Selectorfrom scrapy.http import HtmlResponsehtml="""<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title></title></head><body> <li class="item-"><a href="link.html">first item</a></li> <li class="item-0"><a href="link1.html">first item</a></li> <li class="item-1"><a href="link2.html">second item</a></li></body></html>"""response=HtmlResponse(url='http://example.com', body=html,encoding='utf-8')ret=Selector(response=response).xpath('//li[re:test(@class, "item-\d*")]//@href').extract()print(ret) |
語法規(guī)則:Selector(response=response查詢對(duì)象).xpath(‘//li[re:test(@class, “item-d*”)]//@href’).extract(),即根據(jù)re正則匹配,test即匹配,屬性名是class,匹配的正則表達(dá)式是”item-d*”,然后獲取該標(biāo)簽的href屬性。
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 | #!/usr/bin/env python# -*- coding:utf-8 -*- import scrapyimport hashlibfrom tutorial.items import JinLuoSiItemfrom scrapy.http import Requestfrom scrapy.selector import HtmlXPathSelector class JinLuoSiSpider(scrapy.spiders.Spider):count=0url_set=set() name="jluosi"domain='http://www.jluosi.com'allowed_domains=["jluosi.com"] start_urls=["http://www.jluosi.com:80/ec/goodsDetail.action?jls=QjRDNEIzMzAzOEZFNEE3NQ==",] def parse(self, response):md5_obj=hashlib.md5()md5_obj.update(response.url)md5_url=md5_obj.hexdigest()if md5_url in JinLuoSiSpider.url_set:passelse:JinLuoSiSpider.url_set.add(md5_url)hxs=HtmlXPathSelector(response)if response.url.startswith('http://www.jluosi.com:80/ec/goodsDetail.action'):item=JinLuoSiItem()item['company']=hxs.select('//div[@class="ShopAddress"]/ul/li[1]/text()').extract()item['link']=hxs.select('//div[@class="ShopAddress"]/ul/li[2]/text()').extract()item['qq']=hxs.select('//div[@class="ShopAddress"]//a/@href').re('.*uin=(?P<qq>\d*)&')item['address']=hxs.select('//div[@class="ShopAddress"]/ul/li[4]/text()').extract() item['title']=hxs.select('//h1[@class="goodsDetail_goodsName"]/text()').extract() item['unit']=hxs.select('//table[@class="R_WebDetail_content_tab"]//tr[1]//td[3]/text()').extract()product_list=[]product_tr=hxs.select('//table[@class="R_WebDetail_content_tab"]//tr')for i in range(2,len(product_tr)):temp={'standard':hxs.select('//table[@class="R_WebDetail_content_tab"]//tr[%d]//td[2]/text()' %i).extract()[0].strip(),'price':hxs.select('//table[@class="R_WebDetail_content_tab"]//tr[%d]//td[3]/text()' %i).extract()[0].strip(),}product_list.append(temp) item['product_list']=product_listyield item current_page_urls=hxs.select('//a/@href').extract()for i in range(len(current_page_urls)):url=current_page_urls[i]if url.startswith('http://www.jluosi.com'):url_ab=urlyield Request(url_ab, callback=self.parse) 選擇器規(guī)則Demo 選擇器規(guī)則Demo |
選擇器規(guī)則Demo
12345 | def parse(self, response):from scrapy.http.cookies import CookieJarcookieJar=CookieJar()cookieJar.extract_cookies(response, response.request)print(cookieJar._cookies) |
獲取響應(yīng)cookie
更多選擇器規(guī)則:http://scrapy-chs.readthedocs.io/zh_CN/latest/topics/selectors.html
7、格式化處理
上述實(shí)例只是簡(jiǎn)單的圖片處理,所以在parse方法中直接處理。如果對(duì)于想要獲取更多的數(shù)據(jù)(獲取頁面的價(jià)格、商品名稱、QQ等),則可以利用Scrapy的items將數(shù)據(jù)格式化,然后統(tǒng)一交由pipelines來處理。即不同功能用不同文件實(shí)現(xiàn)。
items:即用戶需要爬取哪些數(shù)據(jù),是用來格式化數(shù)據(jù),并告訴pipelines哪些數(shù)據(jù)需要保存。
示例items.py文件:
12345678910111213141516 | # -*- coding: utf-8 -*- # Define here the models for your scraped items## See documentation in:# http://doc.scrapy.org/en/latest/topics/items.html import scrapy class JieYiCaiItem(scrapy.Item): company=scrapy.Field()title=scrapy.Field()qq=scrapy.Field()info=scrapy.Field()more=scrapy.Field() |
即:需要爬取所有url中的公司名,title,qq,基本信息info,更多信息more。
上述定義模板,以后對(duì)于從請(qǐng)求的源碼中獲取的數(shù)據(jù)同樣按照此結(jié)構(gòu)來獲取,所以在spider中需要有一下操作:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 | #!/usr/bin/env python# -*- coding:utf-8 -*- import scrapyimport hashlibfrom beauty.items import JieYiCaiItemfrom scrapy.http import Requestfrom scrapy.selector import HtmlXPathSelectorfrom scrapy.spiders import CrawlSpider, Rulefrom scrapy.linkextractors import LinkExtractor class JieYiCaiSpider(scrapy.spiders.Spider):count=0url_set=set() name="jieyicai"domain='http://www.jieyicai.com'allowed_domains=["jieyicai.com"] start_urls=["http://www.jieyicai.com",] rules=[#下面是符合規(guī)則的網(wǎng)址,但是不抓取內(nèi)容,只是提取該頁的鏈接(這里網(wǎng)址是虛構(gòu)的,實(shí)際使用時(shí)請(qǐng)?zhí)鎿Q)#Rule(SgmlLinkExtractor(allow=(r'http://test_url/test?page_index=\d+'))),#下面是符合規(guī)則的網(wǎng)址,提取內(nèi)容,(這里網(wǎng)址是虛構(gòu)的,實(shí)際使用時(shí)請(qǐng)?zhí)鎿Q)#Rule(LinkExtractor(allow=(r'http://www.jieyicai.com/Product/Detail.aspx?pid=\d+')), callback="parse"),] def parse(self, response):md5_obj=hashlib.md5()md5_obj.update(response.url)md5_url=md5_obj.hexdigest()if md5_url in JieYiCaiSpider.url_set:passelse:JieYiCaiSpider.url_set.add(md5_url)hxs=HtmlXPathSelector(response)if response.url.startswith('http://www.jieyicai.com/Product/Detail.aspx'):item=JieYiCaiItem()item['company']=hxs.select('//span[@class="username g-fs-14"]/text()').extract()item['qq']=hxs.select('//span[@class="g-left bor1qq"]/a/@href').re('.*uin=(?P<qq>\d*)&')item['info']=hxs.select('//div[@class="padd20 bor1 comard"]/text()').extract()item['more']=hxs.select('//li[@class="style4"]/a/@href').extract()item['title']=hxs.select('//div[@class="g-left prodetail-text"]/h2/text()').extract()yield item current_page_urls=hxs.select('//a/@href').extract()for i in range(len(current_page_urls)):url=current_page_urls[i]if url.startswith('/'):url_ab=JieYiCaiSpider.domain + urlyield Request(url_ab, callback=self.parse) spider spider |
spider
上述代碼中:對(duì)url進(jìn)行md5加密的目的是避免url過長(zhǎng),也方便保存在緩存或數(shù)據(jù)庫中。
此處代碼的關(guān)鍵在于:
將獲取的數(shù)據(jù)封裝在了Item對(duì)象中
yield Item對(duì)象 (一旦parse中執(zhí)行yield Item對(duì)象,則自動(dòng)將該對(duì)象交個(gè)pipelines的類來處理)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 | # -*- coding: utf-8 -*- # Define your item pipelines here## Don't forget to add your pipeline to the ITEM_PIPELINES setting# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import jsonfrom twisted.enterprise import adbapiimport MySQLdb.cursorsimport re mobile_re=re.compile(r'(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}')phone_re=re.compile(r'(\d+-\d+|\d+)') class JsonPipeline(object): def __init__(self):self.file=open('/Users/wupeiqi/PycharmProjects/beauty/beauty/jieyicai.json', 'wb') def process_item(self, item, spider):line="%s %s\n" % (item['company'][0].encode('utf-8'), item['title'][0].encode('utf-8'))self.file.write(line)return item class DBPipeline(object): def __init__(self):self.db_pool=adbapi.ConnectionPool('MySQLdb',db='DbCenter',user='root',passwd='123',cursorclass=MySQLdb.cursors.DictCursor,use_unicode=True) def process_item(self, item, spider):query=self.db_pool.runInteraction(self._conditional_insert, item)query.addErrback(self.handle_error)return item def _conditional_insert(self, tx, item):tx.execute("select nid from company where company=%s", (item['company'][0], ))result=tx.fetchone()if result:passelse:phone_obj=phone_re.search(item['info'][0].strip())phone=phone_obj.group() if phone_obj else ' ' mobile_obj=mobile_re.search(item['info'][1].strip())mobile=mobile_obj.group() if mobile_obj else ' ' values=(item['company'][0],item['qq'][0],phone,mobile,item['info'][2].strip(),item['more'][0])tx.execute("insert into company(company,qq,phone,mobile,address,more) values(%s,%s,%s,%s,%s,%s)", values) def handle_error(self, e):print 'error',e pipelines pipelines |
上述代碼中多個(gè)類的目的是,可以同時(shí)保存在文件和數(shù)據(jù)庫中,保存的優(yōu)先級(jí)可以在配置文件settings中定義。
12345 | ITEM_PIPELINES={'beauty.pipelines.DBPipeline': 300,'beauty.pipelines.JsonPipeline': 100,}# 每行后面的整型值,確定了他們運(yùn)行的順序,item按數(shù)字從低到高的順序,通過pipeline,通常將這些數(shù)字定義在0-1000范圍內(nèi)。 |
總結(jié):本文對(duì)python爬蟲框架Scrapy做了詳細(xì)分析和實(shí)例講解,如果本文對(duì)您有參考價(jià)值,歡迎幫博主點(diǎn)下文章下方的推薦,謝謝!
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。