網絡爬蟲(又被稱為網頁蜘蛛,網絡機器人,在FOAF社區中間,更經常的稱為網頁追逐者),是一種按照一定的規則,自動地抓取萬維網信息的程序或者腳本。另外一些不常使用的名字還有螞蟻、自動索引、模擬程序或者蠕蟲。當然也可以理解為在網絡上爬行的蜘蛛,把互聯網比作一張大網,而爬蟲便是在這網上爬來爬去的蜘蛛,如果遇到資源就會把它取下來,想抓取什么,由你來決定。
首先、要學習python爬蟲要掌握一下幾點:
- python基礎知識
- python中urllib和urllib2庫的用法
- python正則表達式
- python爬蟲框架Scrapy
- Python爬蟲更高級的功能
1、python基礎知識可以在前幾篇有介紹
2、urllib和urllib2庫是學習python爬蟲最基本的庫,利用這個庫可以得到網頁的內容,並對內容用正則表達式提取分析,得到我們想要的結果,
3、python正則表達式
python正則表達式是一種用來匹配字符串的強有力的工具,它的設計是有一種描述性語言來給字符串定義一個規則,凡是符合規則的字符串,我們就可以認為它‘匹配’了,否則,該字符串就是不合法的。
4、爬蟲框架scrap
scrap框架功能簡述如下:
HTML, XML源數據 選擇及提取 的內置支持 提供了一系列在spider之間共享的可復用的過濾器(即 Item Loaders),對智能處理爬取數據提供了內置支持。 通過 feed導出 提供了多格式(JSON、CSV、XML),多存儲后端(FTP、S3、本地文件系統)的內置支持 提供了media pipeline,可以 自動下載 爬取到的數據中的圖片(或者其他資源)。 高擴展性。您可以通過使用 signals ,設計好的API(中間件, extensions, pipelines)來定制實現您的功能。 內置的中間件及擴展為下列功能提供了支持: cookies and session 處理 HTTP 壓縮 HTTP 認證 HTTP 緩存 user-agent模擬 robots.txt 爬取深度限制 針對非英語語系中不標准或者錯誤的編碼聲明, 提供了自動檢測以及健壯的編碼支持。 支持根據模板生成爬蟲。在加速爬蟲創建的同時,保持在大型項目中的代碼更為一致。詳細內容請參閱 genspider 命令。 針對多爬蟲下性能評估、失敗檢測,提供了可擴展的 狀態收集工具 。 提供 交互式shell終端 , 為您測試XPath表達式,編寫和調試爬蟲提供了極大的方便 提供 System service, 簡化在生產環境的部署及運行 內置 Web service, 使您可以監視及控制您的機器 內置 Telnet終端 ,通過在Scrapy進程中鈎入Python終端,使您可以查看並且調試爬蟲 Logging 為您在爬取過程中捕捉錯誤提供了方便 支持 Sitemaps 爬取 具有緩存的DNS解析器
官方文檔:http://doc.scrapy.org/en/latest/
5、簡單的扒下一個網頁。
在網頁中其實就是代碼通過瀏覽器解釋呈現出來,實質是由一段HTML代碼,加JS、CSS,如果把網頁比作一個人,那么HTML便是他的骨架,JS便是他的肌肉,CSS便是它的衣服。所以最重要的部分是存在與HTML中的。下面就說小例子:
import urllib2 response = urllib2.urlopen("http://www.baidu.com") print response.read()
可以直接執行一下感受下爬蟲的魅力。
這里解析一下上面的代碼,首先是utllib2庫里面的urlopen方法,傳入一個url,這個網址是百度的首頁,協議是http協議,當然也可以換成其他的例如:ftp、file、https等等,只是代表了一種訪問控制協議,urlopen一般接受三個參數,參數如下:
urlopen(url, data, timeout)
參數url即為url,data是訪問url時要傳送的數據,timeout是設置超時時間。data和timeout可以不傳送,data默認為空None,timeout默認為socket._GLOBAL_DEFAULT_TIMEOUT。第一個參數url是必須要傳送的,在這個例子里我們傳送了百度的url,執行urlopen方法之后,返回一個response對象,返回信息保存在這里。
print response.read()
response對象有一個read方法,可以返回獲取到此的網頁內容。
如果不加read直接打印就會有如下錯誤:
<addinfourl at 139728495260376 whose fp = <socket._fileobject object at 0x7f1513fb3ad0>>
直接打印出了該對象的描述,所以記得一定要加read方法,否則它不出來內容。
Requset |
Requests 是使用 Apache2 Licensed 許可證的 基於Python開發的HTTP 庫,其在Python內置模塊的基礎上進行了高度的封裝,從而使得Pythoner進行網絡請求時,變得美好了許多,使用Requests可以輕而易舉的完成瀏覽器可有的任何操作。

import urllib2 import json import cookielib def urllib2_request(url, method="GET", cookie="", headers={}, data=None): """ :param url: 要請求的url :param cookie: 請求方式,GET、POST、DELETE、PUT.. :param cookie: 要傳入的cookie,cookie= 'k1=v1;k1=v2' :param headers: 發送數據時攜帶的請求頭,headers = {'ContentType':'application/json; charset=UTF-8'} :param data: 要發送的數據GET方式需要傳入參數,data={'d1': 'v1'} :return: 返回元祖,響應的字符串內容 和 cookiejar對象 對於cookiejar對象,可以使用for循環訪問: for item in cookiejar: print item.name,item.value """ if data: data = json.dumps(data) cookie_jar = cookielib.CookieJar() handler = urllib2.HTTPCookieProcessor(cookie_jar) opener = urllib2.build_opener(handler) opener.addheaders.append(['Cookie', 'k1=v1;k1=v2']) request = urllib2.Request(url=url, data=data, headers=headers) request.get_method = lambda: method response = opener.open(request) origin = response.read() return origin, cookie_jar # GET result = urllib2_request('http://127.0.0.1:8001/index/', method="GET") # POST result = urllib2_request('http://127.0.0.1:8001/index/', method="POST", data= {'k1': 'v1'}) # PUT result = urllib2_request('http://127.0.0.1:8001/index/', method="PUT", data= {'k1': 'v1'})
其實上面的urlopen參數庫傳入一個request請求,它其實就是一個request類的實例,構造時需要傳入url,data等等的內容。通過上面的代碼可以改寫成:
import urllib2 request = urllib2.Request("http://www.baidu.com") response = urllib2.urlopen(request) print response.read()
運行結果是完全一樣的,只不過中間多了一個request對象,推薦大家這么寫,因為在構建請求時還需要加入好多內容,通過構建一個request,服務器響應請求得到應答,這樣顯得邏輯上清晰明確。
POST和GET數據傳送
POST和GET的區別:
最重要的是get方式是直接以鏈接形式訪問,鏈接中包含了所有的參數,當然如果包含了密碼的話是一種不安全的選擇,不過你可以直觀的看到自己提交的內容,POST則不會在網址上顯示所有的參數,不過如果你想直接查看提交了什么就不太方便了。
1、POST方式:
上面已經說過data是傳參的,這里就做一個傳參的實例:
import urllib import urllib2 values = {"username":"1016903103@qq.com","password":"XXXX"} data = urllib.urlencode(values) url = "https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn" request = urllib2.Request(url,data) response = urllib2.urlopen(request) print response.read()
引入了urllib庫,模擬登錄csdn,因為這里還沒有設置頭部header的工作,還有一些參數沒有設置全,所以肯定登錄不上去,只是說一下原理。上例解析:創建了一個字典,名字values,參數設置了username和password,下面利用urllib的urlencode方法將字典編碼,命名為data,狗見request時,傳入兩個參數,url和data,運行程序,即可實現登錄,返回的便是登錄后呈現的頁面內容,上面的字典的定義方式還有一種,和下面的寫法是等價的。
import urllib import urllib2 values = {} values['username'] = "1016903103@qq.com" values['password'] = "XXXX" data = urllib.urlencode(values) url = "http://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn" request = urllib2.Request(url,data) response = urllib2.urlopen(request) print response.read()
舉例:
# 1、基本POST實例 import requests payload = {'key1': 'value1', 'key2': 'value2'} ret = requests.post("http://httpbin.org/post", data=payload) print ret.text # 2、發送請求頭和數據實例 import requests import json url = 'https://api.github.com/some/endpoint' payload = {'some': 'data'} headers = {'content-type': 'application/json'} ret = requests.post(url, data=json.dumps(payload), headers=headers) print ret.text print ret.cookies
向https://api.github.com/some/endpoint發送一個POST請求,將請求和相應相關的內容封裝在 ret 對象中。
2、GET方式:
至於get方式我們可以直接把參數寫到網址上面,直接構建一個帶參數的url出來即可。
import urllib import urllib2 values={} values['username'] = "1016903103@qq.com" values['password']="XXXX" data = urllib.urlencode(values) url = "http://passport.csdn.net/account/login" geturl = url + "?"+data request = urllib2.Request(geturl) response = urllib2.urlopen(request) print response.read()
你可以print geturl,打印輸出一下url,發現其實就是原來的url加?然后加編碼后的參數
http://passport.csdn.net/account/login?username=1016903103%40qq.com&password=XXXX
和我們平常GET訪問方式一模一樣,這樣就實現了數據的get方式傳送。
舉例:
# 1、無參數實例 import requests ret = requests.get('https://github.com/timeline.json') print ret.url print ret.text # 2、有參數實例 import requests payload = {'key1': 'value1', 'key2': 'value2'} ret = requests.get("http://httpbin.org/get", params=payload) print ret.url print ret.text
向 https://github.com/timeline.json 發送一個GET請求,將請求和響應相關均封裝在 ret 對象中。
3、其他請求
requests.get(url, params=None, **kwargs) requests.post(url, data=None, json=None, **kwargs) requests.put(url, data=None, **kwargs) requests.head(url, **kwargs) requests.delete(url, **kwargs) requests.patch(url, data=None, **kwargs) requests.options(url, **kwargs) # 以上方法均是在此方法的基礎上構建 requests.request(method, url, **kwargs)
requests模塊已經將常用的Http請求方法為用戶封裝完成,用戶直接調用其提供的相應方法即可,其中方法的所有參數有:

def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'http://httpbin.org/get') <Response [200]> """ # By using the 'with' statement we are sure the session is closed, thus we # avoid leaving sockets open which can trigger a ResourceWarning in some # cases, and look like a memory leak in others. with sessions.Session() as session: return session.request(method=method, url=url, **kwargs)
更多requests模塊相關的文檔見:http://cn.python-requests.org/zh_CN/latest/
Sxrapy |
Scrapy是一個為了爬取網站數據,提取結構性數據而編寫的應用框架。 其可以應用在數據挖掘,信息處理或存儲歷史數據等一系列的程序中。
其最初是為了頁面抓取 (更確切來說, 網絡抓取 )所設計的, 也可以應用在獲取API所返回的數據(例如 Amazon Associates Web Services ) 或者通用的網絡爬蟲。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交給調度器等待抓取
一、安裝
pip install Scrapy
注:windows平台需要依賴pywin32,請根據自己系統32/64位選擇下載安裝,https://sourceforge.net/projects/pywin32/
二、基本使用
1、創建項目
運行命令:
scrapy startproject your_project_name
自動創建目錄:
project_name/ scrapy.cfg project_name/ __init__.py items.py pipelines.py settings.py spiders/ __init__.py
文件說明:
- scrapy.cfg 項目的配置信息,主要為Scrapy命令行工具提供一個基礎的配置信息。(真正爬蟲相關的配置信息在settings.py文件中)
- items.py 設置數據存儲模板,用於結構化數據,如:Django的Model
- pipelines 數據處理行為,如:一般結構化的數據持久化
- settings.py 配置文件,如:遞歸的層數、並發數,延遲下載等
- spiders 爬蟲目錄,如:創建文件,編寫爬蟲規則
注意:一般創建爬蟲文件時,以網站域名命名
2、編寫爬蟲
在spiders目錄中新建 xiaohuar_spider.py 文件
#!/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 body = response.body unicode_body = response.body_as_unicode()
3、運行
進入project_name目錄,運行命令
scrapy crawl spider_name --nolog
4、遞歸的訪問
以上的爬蟲僅僅是爬去初始頁,而我們爬蟲是需要源源不斷的執行下去,直到所有的網頁被執行完畢
#!/usr/bin/env python # -*- coding:utf-8 -*- import scrapy from scrapy.http import Request from scrapy.selector import HtmlXPathSelector import re import urllib import os class XiaoHuarSpider(scrapy.spiders.Spider): name = "xiaohuar" allowed_domains = ["xiaohuar.com"] start_urls = [ "http://www.xiaohuar.com/list-1-1.html", ] def parse(self, response): # 分析頁面 # 找到頁面中符合規則的內容(校花圖片),保存 # 找到所有的a標簽,再訪問其他a標簽,一層一層的搞下去 hxs = HtmlXPathSelector(response) # 如果url是 http://www.xiaohuar.com/list-1-\d+.html if re.match('http://www.xiaohuar.com/list-1-\d+.html', response.url): items = hxs.select('//div[@class="item_list infinite_scroll"]/div') 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() name = hxs.select('//div[@class="item_list infinite_scroll"]/div[%d]//div[@class="img"]/span/text()' % i).extract() 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')) file_path = os.path.join("/Users/wupeiqi/PycharmProjects/beauty/pic", file_name) urllib.urlretrieve(ab_src, file_path) # 獲取所有的url,繼續訪問,並在其中尋找相同的url all_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)
以上代碼將符合規則的頁面中的圖片保存在指定目錄,並且在HTML源碼中找到所有的其他 a 標簽的href屬性,從而“遞歸”的執行下去,直到所有的頁面都被訪問過為止。以上代碼之所以可以進行“遞歸”的訪問相關URL,關鍵在於parse方法使用了 yield Request對象。
注:可以修改settings.py 中的配置文件,以此來指定“遞歸”的層數,如: DEPTH_LIMIT = 1

#!/usr/bin/env python # -*- coding:utf-8 -*- import scrapy import hashlib from tutorial.items import JinLuoSiItem from scrapy.http import Request from scrapy.selector import HtmlXPathSelector class JinLuoSiSpider(scrapy.spiders.Spider): count = 0 url_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: pass else: 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_list 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('http://www.jluosi.com'): url_ab = url yield Request(url_ab, callback=self.parse)
更多選擇器規則:http://scrapy-chs.readthedocs.io/zh_CN/latest/topics/selectors.html
5、格式化處理
上述實例只是簡單的圖片處理,所以在parse方法中直接處理,如果對於想要獲取更多的數據(獲取頁面的價格,商品名稱、QQ等),則可以利用Scrapy的items將數據格式化,然后統一交由pipelines來處理。
在items.py創建類:
# -*- 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()
上述定義模板,以后對於從請求的源碼中獲取的數據同意按照此結構來獲取,所以在spider中需要有一下操作:

#!/usr/bin/env python # -*- coding:utf-8 -*- import scrapy import hashlib from beauty.items import JieYiCaiItem from scrapy.http import Request from scrapy.selector import HtmlXPathSelector from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class JieYiCaiSpider(scrapy.spiders.Spider): count = 0 url_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: pass else: 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 + url yield Request(url_ab, callback=self.parse)
此處代碼的關鍵在於:
- 將獲取的數據封裝在了Item對象中
- yield Item對象 (一旦parse中執行yield Item對象,則自動將該對象交個pipelines的類來處理)

# -*- 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 json from twisted.enterprise import adbapi import MySQLdb.cursors import 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: pass else: 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中有多個類,到底Scapy會自動執行那個?哈哈哈哈,當然需要先配置了,不然Scapy就蒙逼了。。。
在settings.py中做如下配置:
ITEM_PIPELINES = { 'beauty.pipelines.DBPipeline': 300, 'beauty.pipelines.JsonPipeline': 100, } # 每行后面的整型值,確定了他們運行的順序,item按數字從低到高的順序,通過pipeline,通常將這些數字定義在0-1000范圍內。
更多請參見Scrapy文檔:http://scrapy-chs.readthedocs.io/zh_CN/latest/index.html
文檔參考: http://python.jobbole.com/81336/
http://www.cnblogs.com/wupeiqi/articles/5354900.html