Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
飾模式使用對象組合的方式動態改變或增加對象行為。Go語言借助于匿名組合和非入侵式接口可以很方便實現裝飾模式。使用匿名組合,在裝飾器中不必顯式定義轉調原對象方法。
在這里插入圖片描述
裝飾器模式主要解決繼承關系過于復雜的問題,通過組合來代替繼承,給原始類添加增強功能,這也是判斷裝飾器的一個重要依據,除此之外,裝飾器還有一個特點,可以對原始類嵌套使用多個裝飾器,為了滿足這樣的需求,在設計的時候,裝飾器類需要跟原始繼承同步的抽象類或者接口。
Java IO 通過4個基類,擴展出很多子類, 具體如下:
裝飾器模式相對于簡單的組合關系,有如下特殊點:
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
}
測試用例
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
}
運行結果
=== RUN TestExampleDecorator
res 80
--- PASS: TestExampleDecorator (0.00s)
PASS
在這里插入圖片描述
言:
LDAP輕量目錄訪問協議為用戶管理提供了統一認證服務,解決了長期存在的多套用戶認證系統孤立、繁雜、難以維護的問題。具有簡捷、高效、易用的特性,是用戶認證管理的不二選擇。
一、簡介
LDAP(Lightweight Directory Access Protocol)是基于X.500標準的輕量目錄訪問協議。它比X.500具有更快的查詢速度和更低的資源消耗,精簡靈活,支持TCP/IP協議。LDAP為用戶管理提供了統一認證服務,解決了辦公環境中多套用戶認證和項目管理系統相互獨立分散的難題。
OpenLDAP 是LDAP的開源實現,OpenLDAP目錄中的信息是按照樹形結構進行組織的,具體信息存儲在條目(entry)中,條目是LDAP的基本元素,也是識別名(DN)的屬性集合,DN 具有全局唯一性,用于準確地引用條目,每個條目屬性又包含類型(type)和值(value)。整體架構如圖所示:
二、快速安裝
系統環境:CentOS7.3
主機名:openldap
系統IP:172.16.201.6
管理賬戶信息:dn:cn=Manager,dc=mydomain,dc=com
部署時,可根據實際需求更改以上信息。
2.1.環境準備
OpenLDAP正式部署前,首先對linux系統環境進行如下準備配置,以滿足OpenLDAP安裝運行需求。
1.設置主機名:
hostnamectl set-hostname openldap
主機名可自行設置成任意名字,只需將openldap設置為更改的主機名即可。
2.關閉防火墻和selinux
systemctl stop firewalld systemctl disable firewalld sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
3.配置epel源,配置完成后重啟服務器,以使相關配置生效
yum install epel-release -y reboot
2.2.OpenLDAP安裝
1.安裝ldap相關組件
yum install openldap openldap-servers openldap-clients -y cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG
2.啟動ldap服務
systemctl start slapd systemctl enable slapd systemctl status slapd
slapd即ldap的服務名稱
3.設置ldap管理員用戶密碼
slappasswd -s 111111 {SSHA}AjIAg98NFvRRlhoBOvsfVqMeAGZwi5O9
本次設置密碼為111111,若需要其他密碼直接更改該值即可。記錄執行結果的返回值{SSHA}AjIAg98NFvRRlhoBOvsfVqMeAGZwi5O9,并將該值寫入到后邊生成的rootpwd.ldif文件中。
4.創建管理員用戶配置文件rootpwd.ldif
cat <<EOF>rootpwd.ldif dn: olcDatabase={0}config,cn=config changetype: modify add: olcRootPW olcRootPW: {SSHA}AjIAg98NFvRRlhoBOvsfVqMeAGZwi5O9 EOF
相關參數說明:
olcRootPW參數值為slappasswd命令的結果輸出。
olcRootPW: {SSHA}AjIAg98NFvRRlhoBOvsfVqMeAGZwi5O9指定了屬性值。
ldif文件是LDAP中數據交換的文件格式。文件內容采用的是key-value形式。注意value后面不能有空格。
olc(OnlineConfiguration)表示寫入LDAP后立即生效。
changetype: modify表示修改entry,此外changetype的值也可以是add,delete等。
add: olcRootPW表示對這個entry新增olcRootPW的屬性。
5.導入rootpwd.ldif信息
ldapadd -Y EXTERNAL -H ldapi:/// -f rootpwd.ldif
6.導入schema
schema包含支持特殊場景的相關屬性,可選擇性導入或全部導入
ls /etc/openldap/schema/*.ldif | while read i; do ldapadd -Y EXTERNAL -H ldapi:/// -f $i; done
7.設置默認域
slappasswd -s 111111 {SSHA}7AA7V1xy++LVZcUbBWYYM9/81wfODiIK
本次設置密碼為111111,若需要其他密碼直接更改該值即可。記錄執行結果的
返回值{SSHA}7AA7V1xy++LVZcUbBWYYM9/81wfODiIK
8.新建默認域配置文件
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
設置 olcRootPW參數值為slappwd命令的返回結果:{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"
使用如上命令進行查看時,輸入訪問密碼為:111111.能夠查看到相關返回結果為如下內容,說明OpenLDAP配置成功。可進行相關管理和使用。
[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管理工具
為簡化OpenLDAP使用,提高工作效率,OpenLDAP支持多種管理工具,較常用的有如下兩款ldapadmin工具,可選擇任意一種。
工具一:
1.可在windows電腦上下載管理工具:
http://www.ldapadmin.org/download/ldapadmin.html
2.下載完成后,解壓該文件,直接雙擊運行,輸入LDAP訪問信息。
Host值為OpenLDAP節點ip地址:172.16.201.6.
Base值為:dc=mydomain,dc=com
Username值為:cn=Manager,dc=mydomain,dc=com
Password值為:111111.
其余參數為默認值。填寫完成后可點擊 "Test connection" 以測試是否能夠正常連接。
3.連接成功后可看到OpenLDAP相關信息
之后可直接創建用戶、組,或進行增、刪、改操作。
工具二:
1.在OpenLDAP運行節點安裝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: 修改主機域名 ServerName www.mydomain.com:80 # line 152: 修改成如下內容: AllowOverride All # line 165: 添加可訪問目錄名的文件名稱 DirectoryIndex index.html index.cgi index.php # 在文件末尾增加如下兩部分內容# server's response header ServerTokens Prod # keepalive is ON KeepAlive On
3.啟動Apache服務并設置開機自啟動
systemctl start httpd systemctl enable httpd
4.編輯/etc/phpldapadmin/config.php文件,按如下內容修改:
vi /etc/phpldapadmin/config.php #注釋掉398行,并取消397行的注釋,修改后內容如下: $servers->setValue('login','attr','dn'); // $servers->setValue('login','attr','uid');
5.編輯/etc/httpd/conf.d/phpldapadmin.conf,在第12行加入Require all granted以允許所有IP訪問,被更改部分內容如下:
<Directory/usr/share/phpldapadmin/htdocs> <IfModule mod_authz_core.c> # Apache 2.4 Require local Require all granted </IfModule>
6.重啟Apache服務使配置生效
systemctl restart httpd
7.在瀏覽器輸入OpenLDAP訪問WEB地址:http://172.16.201.6/ldapadmin/
輸入登錄用戶名:cn=Manager,dc=mydomain,dc=com和密碼:111111
8.通過認證后,可直接創建用戶、組,進行增、刪、改操作。
crapy,Python開發的一個快速,高層次的屏幕抓取和web抓取框架,用于抓取web站點并從頁面中提取結構化的數據。Scrapy用途廣泛,可以用于數據挖掘、監測和自動化測試。Scrapy吸引人的地方在于它是一個框架,任何人都可以根據需求方便的修改。它也提供了多種類型爬蟲的基類,如BaseSpider、sitemap爬蟲等,最新版本又提供了web2.0爬蟲的支持。Scratch,是抓取的意思,這個Python的爬蟲框架叫Scrapy,大概也是這個意思吧,就叫它:小刮刮吧。Scrapy 使用了 Twisted異步網絡庫來處理網絡通訊。整體架構大致如下
Scrapy主要包括了以下組件:
引擎(Scrapy)
用來處理整個系統的數據流處理, 觸發事務(框架核心)
調度器(Scheduler)
用來接受引擎發過來的請求, 壓入隊列中, 并在引擎再次請求的時候返回. 可以想像成一個URL(抓取網頁的網址或者說是鏈接)的優先隊列, 由它來決定下一個要抓取的網址是什么, 同時去除重復的網址
下載器(Downloader)
用于下載網頁內容, 并將網頁內容返回給蜘蛛(Scrapy下載器是建立在twisted這個高效的異步模型上的)
爬蟲(Spiders)
爬蟲是主要干活的, 用于從特定的網頁中提取自己需要的信息, 即所謂的實體(Item)。用戶也可以從中提取出鏈接,讓Scrapy繼續抓取下一個頁面
項目管道(Pipeline)
負責處理爬蟲從網頁中抽取的實體,主要的功能是持久化實體、驗證實體的有效性、清除不需要的信息。當頁面被爬蟲解析后,將被發送到項目管道,并經過幾個特定的次序處理數據。
下載器中間件(Downloader Middlewares)
位于Scrapy引擎和下載器之間的框架,主要是處理Scrapy引擎與下載器之間的請求及響應。
爬蟲中間件(Spider Middlewares)
介于Scrapy引擎和爬蟲之間的框架,主要工作是處理蜘蛛的響應輸入和請求輸出。
調度中間件(Scheduler Middewares)
介于Scrapy引擎和調度之間的中間件,從Scrapy引擎發送到調度的請求和響應。
Scrapy運行流程大概如下:
引擎從調度器中取出一個鏈接(URL)用于接下來的抓取
引擎把URL封裝成一個請求(Request)傳給下載器
下載器把資源下載下來,并封裝成應答包(Response)
爬蟲解析Response
解析出實體(Item),則交給實體管道進行進一步的處理
解析出的是鏈接(URL),則把URL交給調度器等待抓取
一、安裝
因為python3并不能完全支持Scrapy,因此為了完美運行Scrapy,我們使用python2.7來編寫和運行Scrapy。
1 | pip install Scrapy |
注:windows平臺需要依賴pywin32,請根據自己系統32/64位選擇下載安裝,https://sourceforge.net/projects/pywin32/
其它可能依賴的安裝包:lxml-3.6.4-cp27-cp27m-win_amd64.whl,VCForPython27.msi百度下載即可
二、基本使用
1、創建項目
運行命令:
1 | scrapy startproject p1(your_project_name) |
2.自動創建目錄的結果:
文件說明:
scrapy.cfg 項目的配置信息,主要為Scrapy命令行工具提供一個基礎的配置信息。(真正爬蟲相關的配置信息在settings.py文件中)
items.py 設置數據存儲模板,用于結構化數據,如:Django的Model
pipelines 數據處理行為,如:一般結構化的數據持久化
settings.py 配置文件,如:遞歸的層數、并發數,延遲下載等
spiders 爬蟲目錄,如:創建文件,編寫爬蟲規則
注意:一般創建爬蟲文件時,以網站域名命名
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 #爬取時請求的urlbody=response.body#返回的htmlunicode_body=response.body_as_unicode()#返回的html unicode編碼 |
備注:
1.爬蟲文件需要定義一個類,并繼承scrapy.spiders.Spider
2.必須定義name,即爬蟲名,如果沒有name,會報錯。因為源碼中是這樣定義的:
3.編寫函數parse,這里需要注意的是,該函數名不能改變,因為Scrapy源碼中默認callback函數的函數名就是parse;
4.定義需要爬取的url,放在列表中,因為可以爬取多個url,Scrapy源碼是一個For循環,從上到下爬取這些url,使用生成器迭代將url發送給下載器下載url的html。源碼截圖:
4、運行
進入p1目錄,運行命令
1 | scrapy crawl xiaohau --nolog |
格式:scrapy crawl+爬蟲名 –nolog即不顯示日志
5.scrapy查詢語法:
當我們爬取大量的網頁,如果自己寫正則匹配,會很麻煩,也很浪費時間,令人欣慰的是,scrapy內部支持更簡單的查詢語法,幫助我們去html中查詢我們需要的標簽和標簽內容以及標簽屬性。下面逐一進行介紹:
查詢子子孫孫中的某個標簽(以div標簽為例)://div
查詢兒子中的某個標簽(以div標簽為例):/div
查詢標簽中帶有某個class屬性的標簽://div[@class=’c1′]即子子孫孫中標簽是div且class=‘c1’的標簽
查詢標簽中帶有某個class=‘c1’并且自定義屬性name=‘alex’的標簽://div[@class=’c1′][@name=’alex’]
查詢某個標簽的文本內容://div/span/text() 即查詢子子孫孫中div下面的span標簽中的文本內容
查詢某個屬性的值(例如查詢a標簽的href屬性)://a/@href
示例代碼:
12345678910111213141516171819 | def parse(self, response):# 分析頁面# 找到頁面中符合規則的內容(校花圖片),保存# 找到所有的a標簽,再訪問其他a標簽,一層一層的搞下去 hxs=HtmlXPathSelector(response)#創建查詢對象 # 如果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中填寫查詢目標,按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標簽的src屬性,即獲取校花圖片地址name=hxs.select('//div[@class="item_list infinite_scroll"]/div[%d]//div[@class="img"]/span/text()' % i).extract() #獲取span的文本內容,即校花姓名school=hxs.select('//div[@class="item_list infinite_scroll"]/div[%d]//div[@class="img"]/div[@class="btns"]/a/text()' % i).extract() #校花學校if src:ab_src="http://www.xiaohuar.com" + src[0]#相對路徑拼接file_name="%s_%s.jpg" % (school[0].encode('utf-8'), name[0].encode('utf-8')) #文件名,因為python27默認編碼格式是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) ,接收文件路徑和需要保存的路徑,會自動去文件路徑下載并保存到我們指定的本地路徑。
5.遞歸爬取網頁
上述代碼僅僅實現了一個url的爬取,如果該url的爬取的內容中包含了其他url,而我們也想對其進行爬取,那么如何實現遞歸爬取網頁呢?
示例代碼:
12345 | # 獲取所有的url,繼續訪問,并在其中尋找相同的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生成器向每一個url發送request請求,并執行返回函數parse,從而遞歸獲取校花圖片和校花姓名學校等信息。
注:可以修改settings.py 中的配置文件,以此來指定“遞歸”的層數,如: 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) |
語法規則:Selector(response=response查詢對象).xpath(‘//li[re:test(@class, “item-d*”)]//@href’).extract(),即根據re正則匹配,test即匹配,屬性名是class,匹配的正則表達式是”item-d*”,然后獲取該標簽的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) 選擇器規則Demo 選擇器規則Demo |
選擇器規則Demo
12345 | def parse(self, response):from scrapy.http.cookies import CookieJarcookieJar=CookieJar()cookieJar.extract_cookies(response, response.request)print(cookieJar._cookies) |
獲取響應cookie
更多選擇器規則:http://scrapy-chs.readthedocs.io/zh_CN/latest/topics/selectors.html
7、格式化處理
上述實例只是簡單的圖片處理,所以在parse方法中直接處理。如果對于想要獲取更多的數據(獲取頁面的價格、商品名稱、QQ等),則可以利用Scrapy的items將數據格式化,然后統一交由pipelines來處理。即不同功能用不同文件實現。
items:即用戶需要爬取哪些數據,是用來格式化數據,并告訴pipelines哪些數據需要保存。
示例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。
上述定義模板,以后對于從請求的源碼中獲取的數據同樣按照此結構來獲取,所以在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=[#下面是符合規則的網址,但是不抓取內容,只是提取該頁的鏈接(這里網址是虛構的,實際使用時請替換)#Rule(SgmlLinkExtractor(allow=(r'http://test_url/test?page_index=\d+'))),#下面是符合規則的網址,提取內容,(這里網址是虛構的,實際使用時請替換)#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
上述代碼中:對url進行md5加密的目的是避免url過長,也方便保存在緩存或數據庫中。
此處代碼的關鍵在于:
將獲取的數據封裝在了Item對象中
yield Item對象 (一旦parse中執行yield Item對象,則自動將該對象交個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 |
上述代碼中多個類的目的是,可以同時保存在文件和數據庫中,保存的優先級可以在配置文件settings中定義。
12345 | ITEM_PIPELINES={'beauty.pipelines.DBPipeline': 300,'beauty.pipelines.JsonPipeline': 100,}# 每行后面的整型值,確定了他們運行的順序,item按數字從低到高的順序,通過pipeline,通常將這些數字定義在0-1000范圍內。 |
總結:本文對python爬蟲框架Scrapy做了詳細分析和實例講解,如果本文對您有參考價值,歡迎幫博主點下文章下方的推薦,謝謝!
*請認真填寫需求信息,我們會在24小時內與您取得聯系。