Python之路【第二十三篇】爬蟲

difference between urllib and urllib2

本身翻譯的裝逼必備 html

What is the difference between urllib and urllib2 modules of Python?
#python的urllib2模塊和urllib模塊之間有什麼不一樣呢?
You might be intrigued by the existence of two separate URL modules in Python - urllib and urllib2. Even more intriguing: they are not alternatives for each other. 
So what is the difference between urllib and urllib2, and do we need them both?
#這兩個模塊你可能好奇,他們不是互相替代的模塊。因此什麼是他們之間的不一樣呢?何時咱們使用他們?

urllib and urllib2 are both Python modules that do URL request related stuff but offer different functionalities. Their two most significant differences are listed below:
#urlib和urlib2他們都是訪問URL相關請求功能的模塊,下面列出了他們之間的重要差別:
urllib2 can accept a Request object to set the headers for a URL request, urllib accepts only a URL. That means, you cannot masquerade your User Agent string etc.
#urlib2 能夠接受請求對象去設置這個請求的頭部,urlib僅能接收一個URL意思是你不能假裝你的用戶代理字符串。
urllib provides the urlencode method which is used for the generation of GET query strings, urllib2 doesn't have such a function. This is one of the reasons why urllib is often used along with urllib2.
#urlib 提供了 urlencode 方法用戶生成和查詢字符串,urlib2不支持這個功能,這是爲何經常urlib和urlib2一塊兒使用的緣由
For other differences between urllib and urllib2 refer to their documentations, the links are given in the References section.
#看下面的連接
Tip: if you are planning to do HTTP stuff only, check out httplib2, it is much better than httplib or urllib or urllib2.
#若是你僅僅是要獲取http頁面的東西的話,看看httplib2,它是比httplib or urlib or urlib2 更好的~~

在查詢的時候看到的文章很不錯:python

http://www.hacksparrow.com/python-difference-between-urllib-and-urllib2.htmlgit

Referencesgithub

  1. urllib
  2. urllib2

在Python3中合併了 urllib 和 urllib2, 統一命名爲 urllib 了web

urllib

整個Urllib的源碼也就1000來行能夠本身看下源碼~~,而且urllib2和urllib同樣也就一個文件~編程

一、urllib.urlopen(url, data=None, proxies=None, context=None)json

打開一個url的方法,返回一個文件對象,而後能夠進行相似文件對象的操做。 windows

import urllib

f = urllib.urlopen('http://www.baidu.com/')

content = f.readlines()
print content

對象返回的對象提供的方法以下:api

#這些方法的使用方式與文件對象徹底同樣
read() , readline() ,readlines() , fileno() , close() 

#返回一個請求頭信息
content = f.info()
print content
'''
info方法內部調用的是headers方法
    def info(self):
        return self.headers
'''
#返回請求的狀態碼信息
content = f.getcode()
print content

#返回請求的url信息
content = f.geturl()
print content

 二、urllib.urlencode(query) 將URL中的鍵值對一連接符&劃分瀏覽器

>>> urllib.urlencode({'word':'luotianshuai','age':18})
'age=18&word=luotianshuai'

因此咱們能夠結合urllib.urlopen來實現GET和POST請求

GET

import urllib

params = urllib.urlencode({'word':'luotianshuai','age':18})
'''
>>> urllib.urlencode({'word':'luotianshuai','age':18})
'age=18&word=luotianshuai'
'''
f = urllib.urlopen('http://zhidao.baidu.com/search?%s' % params)
print f.read()

POST 

import urllib

params = urllib.urlencode({'word':'luotianshuai','age':18})
'''
>>> urllib.urlencode({'word':'luotianshuai','age':18})
'age=18&word=luotianshuai'
'''
f = urllib.urlopen('http://zhidao.baidu.com/search',params)
for i in f.read().split('\n'):
    print i

urllib2

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'})

封裝urllib請求

requests

上面是吧urllib2進行了封裝並無實現上傳文件要是上傳文件的話就更麻煩了,因此又出現了一個模塊requests上面的操做就至關於底層的東西了,requests對其進行了封裝!

因此咱們只需安裝個包就OK了~

# 一、基本POST實例
 
import requests
 
payload = {'key1': 'value1', 'key2': 'value2'}
ret = requests.post("http://httpbin.org/post", data=payload)
 
print ret.text
 
 
# 二、發送請求頭和數據實例
 
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、其餘請求

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/ 

結合reques能夠進行瀏覽器如出一轍的工做!

#!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'luotianshuai'

import requests
import json


login_dic = {
    'email':'shuaige@qq.com',
    'password':'shuaige!',
    '_ref':'frame',
}

login_ret = requests.post(url='https://huaban.com/auth/',
                          data=login_dic,
                          )
print login_ret.text

print '*' * 50

check_my_info = requests.get(url='http://huaban.com/ugb8cx9ky3/following/')
print check_my_info.text

舉例來講若是是在web上聊天原理上也是經過get或者post發送數據過去那麼咱們就能夠經過reques來進行發送消息訪問各類url 大讚~~

scrapy

Scrapy是一個爲了爬取網站數據,提取結構性數據而編寫的應用框架。 其能夠應用在數據挖掘,信息處理或存儲歷史數據等一系列的程序中。
其最初是爲了頁面抓取 (更確切來講, 網絡抓取 )所設計的, 也能夠應用在獲取API所返回的數據(例如 Amazon Associates Web Services ) 或者通用的網絡爬蟲。Scrapy用途普遍,能夠用於數據挖掘、監測和自動化測試。

requests本質就是就是發送http請求,若是在requests基礎上作個封裝,我去某個網站或者某個域名一直去發送請求找到全部的url,下載東西的請求在寫個方法源源不斷的下載東西!這樣咱們就寫了個框架。

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中的數據流由執行引擎控制,其過程以下:

  1. 引擎打開一個網站(open a domain),找處處理該網站的Spider並向該spider請求第一個要爬取的URL(s)。
  2. 引擎從Spider中獲取到第一個要爬取的URL並在調度器(Scheduler)以Request調度。
  3. 引擎向調度器請求下一個要爬取的URL。
  4. 調度器返回下一個要爬取的URL給引擎,引擎將URL經過下載中間件(請求(request)方向)轉發給下載器(Downloader)。
  5. 一旦頁面下載完畢,下載器生成一個該頁面的Response,並將其經過下載中間件(返回(response)方向)發送給引擎。
  6. 引擎從下載器中接收到Response並經過Spider中間件(輸入方向)發送給Spider處理。
  7. Spider處理Response並返回爬取到的Item及(跟進的)新的Request給引擎。
  8. 引擎將(Spider返回的)爬取到的Item給Item Pipeline,將(Spider返回的)Request給調度器。
  9. (從第二步)重複直到調度器中沒有更多地request,引擎關閉該網站。

1、安裝

pip install Scrapy
#windows平臺須要依賴pywin32,請根據本身系統32/64位選擇下載安裝,https://sourceforge.net/projects/pywin32/

在MAC安裝的時候遇到了個有趣的問題本身總結了下面的文檔~~,順便贊下Google

I resolved a problem ,when you you install scrapy-----{mac os system}, maybe you will get error like:

'''
sted>=10.0.0->Scrapy)
Installing collected packages: six, w3lib, parsel, PyDispatcher, Twisted, Scrapy
  Found existing installation: six 1.4.1
    DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling six-1.4.1:
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/basecommand.py", line 209, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/commands/install.py", line 317, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/req/req_set.py", line 726, in install
    requirement.uninstall(auto_confirm=True)
  File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/req/req_install.py", line 746, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/req/req_uninstall.py", line 115, in remove
    renames(path, new_path)
  File "/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg/pip/utils/__init__.py", line 267, in renames
    shutil.move(old, new)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
    copy2(src, real_dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
    copystat(src, dst)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
    os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-ZVi5QO-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'
You are using pip version 8.1.1, however version 8.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
LuoTimdeMacBook-Pro-2:~ luotim$ sudo pip install Scrapy --ingnore-installed six

'''

Six is a Python 2 and 3 compatibility library.

frist thanks google and what's fuck baidu ! so you should be do this to resolved the problem:
一、Download the six-1.10.0.tar.gz package
wget https://pypi.python.org/packages/b3/b2/238e2590826bfdd113244a40d9d3eb26918bd798fc187e2360a8367068db/six-1.10.0.tar.gz#md5=34eed507548117b2ab523ab14b2f8b55

2、UnZip software package
tar -zxvf six-1.10.0.tar.gz

3、Use this command to install it.
cd cd six-1.10.0
sudo python setup.py install

http://stackoverflow.com/questions/29485741/unable-to-upgrade-python-six-package-in-mac-osx-10-10-2

2、基本使用

一、建立項目

運行命令他和Django同樣要想穿件Project必須執行下面的命令:

scrapy startproject your_project_name

將會在執行命令的目錄自動建立以下文件:

LuoTimdeMacBook-Pro-2:day26 luotim$ tree meinv/
meinv/
├── meinv
│   ├── __init__.py
│   ├── items.py
│   ├── pipelines.py
│   ├── settings.py
│   └── spiders
│       └── __init__.py
└── scrapy.cfg

2 directories, 6 files
  • scrapy.cfg  項目的配置信息,主要爲Scrapy命令行工具提供一個基礎的配置信息。(真正爬蟲相關的配置信息在settings.py文件中)
  • items.py    設置數據存儲模板,用於結構化數據,如:Django的Model
  • pipelines    數據處理行爲,如:通常結構化的數據持久化
  • settings.py 配置文件,如:遞歸的層數、併發數,延遲下載等
  • spiders      爬蟲目錄,如:建立文件,編寫爬蟲規則

 二、編寫爬蟲

注意:通常建立爬蟲文件時,以網站域名命名

在spiders目錄中新建 xiaohuar_spider.py 文件

#!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'luotianshuai'

import scrapy


#定義一個類
class XiaoHuarSpider(scrapy.spiders.Spider):
    #這個類是有名字的能夠隨便定義
    name = "xiaohuar"
    #定義限制只能在這個域名下爬
    allowed_domains = ["xiaohuar.com"]
    #起始URL
    start_urls = [
        "http://www.xiaohuar.com/hua/",
    ]

    '''
    #當程序運行的時候,會自動執行咱們定義的上面的類,並訪問start_urls並下載裏面的內容封裝起來傳給parese中的"response"
    這個都是scrapy內部乾的
    '''

    def parse(self, response):
        # print(response, type(response))
        # from scrapy.http.response.html import HtmlResponse
        # print(response.body_as_unicode())

        '''而後就能夠經過response獲取此次請求的相關信息'''
        current_url = response.url
        body = response.body
        unicode_body = response.body_as_unicode()

三、運行

進入project_name目錄,運行命令!

#進入scrapy項目目錄裏
cd meinv

#執行命令,這個spider_name就是在咱們定義爬蟲的那個類裏的name字段
scrapy crawl spider_name --nolog

四、遞歸的訪問

以上的爬蟲僅僅是爬去初始頁,而咱們爬蟲是須要源源不斷的執行下去,直到全部的網頁被執行完畢

 

#!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = 'luotianshuai'

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):
        '''
        1 分析頁面
        2 找到頁面中符合規則的內容(校花圖片),保存
        3 找到全部的a標籤,再訪問其餘a標籤,一層一層的搞下去
        '''



        hxs = HtmlXPathSelector(response)
        '''
        hxs = HtmlXPathSelector(response)
        #格式化源碼
        #之前我們從html頁面中去獲取某些數據的時候須要用正則,如今不用了scrapy給我們提供了類選擇器
        #只要建立一個對象而後他就會頁面中去找,他支持  --鏈式編程--  相似於找:
        div[@class='xxx]的標籤 若是在加個/a  就是div[@class='xxx]/a 就是div下的class='xxx'的下面的a標籤
        '''

        # 若是url是 http://www.xiaohuar.com/list-1-\d+.html經過正則去判斷,這裏首選須要瞭解的是
        # 這個網站的URL設計就能夠了,這是符合URL的
        if re.match('http://www.xiaohuar.com/list-1-\d+.html', response.url):

            #這裏是調用hxs而後去找到div下class='item_list infinite_scroll'下的div,
            #這個一樣也是須要看下網頁的設計結構,校花網的設計結構就是這樣的嘿嘿....
            items = hxs.select('//div[@class="item_list infinite_scroll"]/div')


            for i in range(len(items)):
                #這個校花裏的DIV是能夠經過索引去取值的
                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_name爲文件
                    urllib.urlretrieve(ab_src, file_name)

        # 獲取全部的url,繼續訪問,並在其中尋找相同的url
        all_urls = hxs.select('//a/@href').extract()  #查找全部的A標籤有href屬性的URL
        #去循環他
        for url in all_urls:
            #而且這裏在加了一個判斷,也能夠不加,而且符合
            if url.startswith('http://www.xiaohuar.com/list-1-'):
                #若是你返回了一個URL而且有callback就會去遞歸,還去執行self.parse
                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)
選擇器demo

更多選擇器規則:http://scrapy-chs.readthedocs.io/zh_CN/latest/topics/selectors.html

 

五、格式化處理

上述實例只是簡單的圖片處理,因此在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範圍內。

 

更多請參見

武sir博客:http://www.cnblogs.com/wupeiqi/articles/5354900.html    

Scrapy文檔:http://scrapy-chs.readthedocs.io/zh_CN/latest/index.html

相關文章
相關標籤/搜索