爬蟲的入門以及scrapy

来源:http://www.cnblogs.com/kading/archive/2016/12/24/6217857.html
-Advertisement-
Play Games

一、簡介 網路爬蟲(又被稱為網頁蜘蛛,網路機器人,在FOAF社區中間,更經常的稱為網頁追逐者),是一種按照一定的規則,自動地抓取萬維網信息的程式或者腳本。另外一些不常使用的名字還有螞蟻、自動索引、模擬程式或者蠕蟲。 二、requests Python標準庫中提供了:urllib、urllib2、ht ...


一、簡介

網路爬蟲(又被稱為網頁蜘蛛,網路機器人,在FOAF社區中間,更經常的稱為網頁追逐者),是一種按照一定的規則,自動地抓取萬維網信息的程式或者腳本。另外一些不常使用的名字還有螞蟻、自動索引、模擬程式或者蠕蟲。

二、requests

Python標準庫中提供了:urllib、urllib2、httplib等模塊以供Http請求,但是,它的 API 太渣了。它是為另一個時代、另一個互聯網所創建的。它需要巨量的工作,甚至包括各種方法覆蓋,來完成最簡單的任務。

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

Requests 是使用 Apache2 Licensed 許可證的 基於Python開發的HTTP 庫,其在Python內置模塊的基礎上進行了高度的封裝,從而使得Pythoner進行網路請求時,變得美好了許多,使用Requests可以輕而易舉的完成瀏覽器可有的任何操作。

1、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 對象中。

2、post

# 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

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/

自動登錄抽屜並點贊 

### 1、首先登陸任何頁面,獲取cookie
 
i1 = requests.get(url= "http://dig.chouti.com/help/service")
 
### 2、用戶登陸,攜帶上一次的cookie,後臺對cookie中的 gpsd 進行授權
i2 = requests.post(
    url= "http://dig.chouti.com/login",
    data= {
        'phone': "86手機號",
        'password': "密碼",
        'oneMonth': ""
    },
    cookies = i1.cookies.get_dict()
)
 
### 3、點贊(只需要攜帶已經被授權的gpsd即可)
gpsd = i1.cookies.get_dict()['gpsd']
i3 = requests.post(
    url="http://dig.chouti.com/link/vote?linksId=8589523",
    cookies={'gpsd': gpsd}
)
print(i3.text)

 

“破解”微信公眾號

“破解”微信公眾號其實就是使用Python代碼自動實現【登陸公眾號】->【獲取觀眾用戶】-> 【向關註用戶發送消息】。

註:只能向48小時內有互動的粉絲主動推送消息

a、自動登錄

 

分析對於Web登陸頁面,用戶登陸驗證時僅做瞭如下操作:

    • 登陸的URL:https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN
    • POST的數據為:

          {
               'username': 用戶名,
               'pwd': 密碼的MD5值,
               'imgcode': "", 
               'f': 'json'
          }
      註:imgcode是需要提供的驗證碼,預設無需驗證碼,只有在多次登陸未成功時,才需要用戶提供驗證碼才能登陸

    • POST的請求頭的Referer值,微信後臺用次來檢查是誰發送來的請求
    • 請求發送並登陸成功後,獲取用戶響應的cookie,以後操作其他頁面時需要攜帶此cookie 
    • 請求發送並登陸成功後,獲取用戶相應的內容中的token

 

登錄代碼

# -*- coding:utf-8 -*- 
import requests
import time
import hashlib


def _password(pwd):
    ha = hashlib.md5()
    ha.update(pwd)
    return ha.hexdigest()

def login():
    
    login_dict = {
        'username': "用戶名",
        'pwd': _password("密碼"),
        'imgcode': "",
        'f': 'json'
    }

    login_res = requests.post(
        url= "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN",
        data=login_dict,
        headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'})

    # 登陸成功之後獲取伺服器響應的cookie
    resp_cookies_dict = login_res.cookies.get_dict()
    # 登陸成功後,獲取伺服器響應的內容
    resp_text = login_res.text
    # 登陸成功後,獲取token
    token = re.findall(".*token=(\d+)", resp_text)[0]

    print resp_text
    print token
    print resp_cookies_dict

login()

登陸成功獲取的相應內容如下:

響應內容:
{"base_resp":{"ret":0,"err_msg":"ok"},"redirect_url":"\/cgi-bin\/home?t=home\/index&lang=zh_CN&token=537908795"}
 
響應cookie:
{'data_bizuin': '3016804678', 'bizuin': '3016804678', 'data_ticket': 'CaoX+QA0ZA9LRZ4YM3zZkvedyCY8mZi0XlLonPwvBGkX0/jY/FZgmGTq6xGuQk4H', 'slave_user': 'gh_5abeaed48d10', 'slave_sid': 'elNLbU1TZHRPWDNXSWdNc2FjckUxalM0Y000amtTamlJOUliSnRnWGRCdjFseV9uQkl5cUpHYkxqaGJNcERtYnM2WjdFT1pQckNwMFNfUW5fUzVZZnFlWGpSRFlVRF9obThtZlBwYnRIVGt6cnNGbUJsNTNIdTlIc2JJU29QM2FPaHZjcTcya0F6UWRhQkhO'}

b、訪問其他頁面獲取用戶信息

分析用戶管理頁面,通過Pyhton代碼以Get方式訪問此頁面,分析響應到的 HTML 代碼,從中獲取用戶信息:

    • 獲取用戶的URL:https://mp.weixin.qq.com/cgi-bin/user_tag?action=get_all_data&lang=zh_CN&token=登陸時獲取的token
    • 發送GET請求時,需要攜帶登陸成功後獲取的cookie
{'data_bizuin': '3016804678', 'bizuin': '3016804678', 'data_ticket': 'C4YM3zZ...

 

    • 獲取當前請求的響應的html代碼
    • 通過正則表達式獲取html中的指定內容(Python的模塊Beautiful Soup)
    • 獲取html中每個用戶的 data-fakeid屬性,該值是用戶的唯一標識,通過它可向用戶推送消息

代碼實現

# -*- coding:utf-8 -*- 
import requests
import time
import hashlib
import json
import re

LOGIN_COOKIES_DICT = {}

def _password(pwd):
    ha = hashlib.md5()
    ha.update(pwd)
    return ha.hexdigest()

def login():
    
    login_dict = {
        'username': "用戶名",
        'pwd': _password("密碼"),
        'imgcode': "",
        'f': 'json'
    }

    login_res = requests.post(
        url= "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN",
        data=login_dict,
        headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'})

    # 登陸成功之後獲取伺服器響應的cookie
    resp_cookies_dict = login_res.cookies.get_dict()
    # 登陸成功後,獲取伺服器響應的內容
    resp_text = login_res.text
    # 登陸成功後,獲取token
    token = re.findall(".*token=(\d+)", resp_text)[0]

    return {'token': token, 'cookies': resp_cookies_dict}


def standard_user_list(content):
    content = re.sub('\s*', '', content)
    content = re.sub('\n*', '', content)
    data = re.findall("""cgiData=(.*);seajs""", content)[0]
    data = data.strip()
    while True:
        temp = re.split('({)(\w+)(:)', data, 1)
        if len(temp) == 5:
            temp[2] = '"' + temp[2] + '"'
            data = ''.join(temp)
        else:
            break

    while True:
        temp = re.split('(,)(\w+)(:)', data, 1)
        if len(temp) == 5:
            temp[2] = '"' + temp[2] + '"'
            data = ''.join(temp)
        else:
            break

    data = re.sub('\*\d+', "", data)
    ret = json.loads(data)
    return ret


def get_user_list():

    login_dict = login()
    LOGIN_COOKIES_DICT.update(login_dict)

    login_cookie_dict = login_dict['cookies']
    res_user_list = requests.get(
        url= "https://mp.weixin.qq.com/cgi-bin/user_tag",
        params = {"action": "get_all_data", "lang": "zh_CN", "token": login_dict['token']},
        cookies = login_cookie_dict,
        headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'}
    )
    user_info = standard_user_list(res_user_list.text)
    for item in user_info['user_list']:
        print "%s %s " % (item['nick_name'],item['id'],)
    
get_user_list()

c、發送消息

分析給用戶發送消息的頁面,從網路請求中剖析得到發送消息的URL,從而使用Python代碼發送消息:

  • 發送消息的URL:https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&token=登陸時獲取的token放在此處&lang=zh_CN
  • 從登陸時相應的內容中獲取:token和cookie
  • 從用戶列表中獲取某個用戶唯一標識: fake_id
  • 封裝消息,併發送POST請求
send_dict = {
    'token': 登陸時獲取的token,
    'lang': "zh_CN",
    'f': 'json',
    'ajax': 1,
    'random': "0.5322618900912392",
    'type': 1,
    'content': 要發送的內容,
    'tofakeid': 用戶列表中獲取的用戶的ID,
    'imgcode': ''
}

發送消息代碼

# -*- coding:utf-8 -*- 
import requests
import time
import hashlib
import json
import re

LOGIN_COOKIES_DICT = {}

def _password(pwd):
    ha = hashlib.md5()
    ha.update(pwd)
    return ha.hexdigest()

def login():
    
    login_dict = {
        'username': "用戶名",
        'pwd': _password("密碼"),
        'imgcode': "",
        'f': 'json'
    }

    login_res = requests.post(
        url= "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN",
        data=login_dict,
        headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'})

    # 登陸成功之後獲取伺服器響應的cookie
    resp_cookies_dict = login_res.cookies.get_dict()
    # 登陸成功後,獲取伺服器響應的內容
    resp_text = login_res.text
    # 登陸成功後,獲取token
    token = re.findall(".*token=(\d+)", resp_text)[0]

    return {'token': token, 'cookies': resp_cookies_dict}


def standard_user_list(content):
    content = re.sub('\s*', '', content)
    content = re.sub('\n*', '', content)
    data = re.findall("""cgiData=(.*);seajs""", content)[0]
    data = data.strip()
    while True:
        temp = re.split('({)(\w+)(:)', data, 1)
        if len(temp) == 5:
            temp[2] = '"' + temp[2] + '"'
            data = ''.join(temp)
        else:
            break

    while True:
        temp = re.split('(,)(\w+)(:)', data, 1)
        if len(temp) == 5:
            temp[2] = '"' + temp[2] + '"'
            data = ''.join(temp)
        else:
            break

    data = re.sub('\*\d+', "", data)
    ret = json.loads(data)
    return ret


def get_user_list():

    login_dict = login()
    LOGIN_COOKIES_DICT.update(login_dict)

    login_cookie_dict = login_dict['cookies']
    res_user_list = requests.get(
        url= "https://mp.weixin.qq.com/cgi-bin/user_tag",
        params = {"action": "get_all_data", "lang": "zh_CN", "token": login_dict['token']},
        cookies = login_cookie_dict,
        headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'}
    )
    user_info = standard_user_list(res_user_list.text)
    for item in user_info['user_list']:
        print "%s %s " % (item['nick_name'],item['id'],)
    

def send_msg(user_fake_id, content='啥也沒發'):

    login_dict = LOGIN_COOKIES_DICT
    
    token = login_dict['token']
    login_cookie_dict = login_dict['cookies']

    send_dict = {
        'token': token,
        'lang': "zh_CN",
        'f': 'json',
        'ajax': 1,
        'random': "0.5322618900912392",
        'type': 1,
        'content': content,
        'tofakeid': user_fake_id,
        'imgcode': ''
    }
   
    send_url = "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&token=%s&lang=zh_CN" % (token,)
    message_list = requests.post(
        url=send_url, 
        data=send_dict, 
        cookies=login_cookie_dict, 
        headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'}
    )


get_user_list()
fake_id = raw_input('請輸入用戶ID:')
content = raw_input('請輸入消息內容:')
send_msg(fake_id, content)

以上就是“破解”微信公眾號的整個過程,通過Python代碼實現了自動【登陸微信公眾號平臺】【獲取用戶列表】【指定用戶發送消息】。

三、scrapy

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運行流程大概如下:

  1. 引擎從調度器中取出一個鏈接(URL)用於接下來的抓取
  2. 引擎把URL封裝成一個請求(Request)傳給下載器
  3. 下載器把資源下載下來,並封裝成應答包(Response)
  4. 爬蟲解析Response
  5. 解析出實體(Item),則交給實體管道進行進一步的處理
  6. 解析出的是鏈接(URL),則把URL交給調度器等待抓取

1、安裝

pip install Scrapy

註:windows平臺需要依賴pywin32,請根據自己系統32/64位選擇下載安裝,https://sourceforge.net/projects/pywin32/

2、基本使用

創建項目

運行命令:

scrapy startproject your_project_name

自動創建目錄:

roject_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      爬蟲目錄,如:創建文件,編寫爬蟲規則

註意:一般創建爬蟲文件時,以網站功能變數名稱命名

#!/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()

 

編寫爬蟲

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

、運行

進入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

正則選擇器

from scrapy.selector import Selector
from scrapy.http import HtmlResponse
html = """<!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)

選擇器規則代碼

#!/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 =	   

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • http://blog.leanote.com/yljiang ...
  • 1.三者在建立新字元串速度方面的比較: StringBuilder > StringBuffer > String 2.線程安全性: StringBuilder:線程非安全的 StringBuffer:線程安全的 單線程操作使用 StringBuilder 多線程操作使用 StringBuffer ...
  • 1.String(字元串) string類型是二進位安全的。意思是redis的string可以包含任何數據。比如jpg圖片或者序列化的對象 。 string類型是Redis最基本的數據類型,一個redis中字元串value最多可以是512M 2.Hash(哈希) Redis hash 是一個鍵值對集 ...
  • 為了方便管理員和工程師調整Solr的配置和訪問線上文檔和其他的幫助,Solr提供了一個Web界面去查看Solr的配置詳情,運行查詢語句和分析文檔欄位。這個界面在第三篇裡面提到過就是管理員界面(以下簡稱Admin UI),如下圖所示: 可以看出Admin UI的界面還是比較複雜的。下麵將分別就界面的各 ...
  • 一、準備文件 UCenter_1.6.0_SC_UTF8 二、項目文件位置 a. UCenter_1.6.0_SC_UTF8\upload\ 下 所有文件 複製到項目根目錄,並安裝UCenter b. UCenter_1.6.0_SC_UTF8\advanced\examples\ 下 Api(文件 ...
  • //獲取兩個日期之間的天數private int daysBetween(Date now, Date returnDate) { Calendar cNow = Calendar.getInstance(); Calendar cReturnDate = Calendar.getInstance( ...
  • 1、打開maven存放文件夾找到 conf ->settings.xml 2、maven下載文件預設存放在c盤,可以配置放在別的磁碟 還是settings.xml文件 找到 <localRepository> 複製出來並修改地址 (1)為預設存放路徑 (2)為改後存放路徑 2、idea中配置mave ...
  • idea版本:2016.3 maven: apache-maven-3.3.9 tomcat:apache-tomcat-8.5.8 1、tomcat.apache.org 下載tomcat http://maven.apache.org/download.cgi 下載maven 下載解壓放在專門j ...
一周排行
    -Advertisement-
    Play Games
  • 前言 推薦一款基於.NET 8、WPF、Prism.DryIoc、MVVM設計模式、Blazor以及MySQL資料庫構建的企業級工作流系統的WPF客戶端框架-AIStudio.Wpf.AClient 6.0。 項目介紹 框架採用了 Prism 框架來實現 MVVM 模式,不僅簡化了 MVVM 的典型 ...
  • 先看一下效果吧: 我們直接通過改造一下原版的TreeView來實現上面這個效果 我們先創建一個普通的TreeView 代碼很簡單: <TreeView> <TreeViewItem Header="人事部"/> <TreeViewItem Header="技術部"> <TreeViewItem He ...
  • 1. 生成式 AI 簡介 https://imp.i384100.net/LXYmq3 2. Python 語言 https://imp.i384100.net/5gmXXo 3. 統計和 R https://youtu.be/ANMuuq502rE?si=hw9GT6JVzMhRvBbF 4. 數 ...
  • 本文為大家介紹下.NET解壓/壓縮zip文件。雖然解壓縮不是啥核心技術,但壓縮性能以及進度處理還是需要關註下,針對使用較多的zip開源組件驗證,給大家提供個技術選型參考 之前在《.NET WebSocket高併發通信阻塞問題 - 唐宋元明清2188 - 博客園 (cnblogs.com)》講過,團隊 ...
  • 之前寫過兩篇關於Roslyn源生成器生成源代碼的用例,今天使用Roslyn的代碼修複器CodeFixProvider實現一個cs文件頭部註釋的功能, 代碼修複器會同時涉及到CodeFixProvider和DiagnosticAnalyzer, 實現FileHeaderAnalyzer 首先我們知道修 ...
  • 在軟體行業,經常會聽到一句話“文不如表,表不如圖”說明瞭圖形在軟體應用中的重要性。同樣在WPF開發中,為了程式美觀或者業務需要,經常會用到各種個樣的圖形。今天以一些簡單的小例子,簡述WPF開發中幾何圖形(Geometry)相關內容,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 在 C# 中使用 RabbitMQ 通過簡訊發送重置後的密碼到用戶的手機號上,你可以按照以下步驟進行 1.安裝 RabbitMQ 客戶端庫 首先,確保你已經安裝了 RabbitMQ 客戶端庫。你可以通過 NuGet 包管理器來安裝: dotnet add package RabbitMQ.Clien ...
  • 1.下載 Protocol Buffers 編譯器(protoc) 前往 Protocol Buffers GitHub Releases 頁面。在 "Assets" 下找到適合您系統的壓縮文件,通常為 protoc-{version}-win32.zip 或 protoc-{version}-wi ...
  • 簡介 在現代微服務架構中,服務發現(Service Discovery)是一項關鍵功能。它允許微服務動態地找到彼此,而無需依賴硬編碼的地址。以前如果你搜 .NET Service Discovery,大概率會搜到一大堆 Eureka,Consul 等的文章。現在微軟為我們帶來了一個官方的包:Micr ...
  • ZY樹洞 前言 ZY樹洞是一個基於.NET Core開發的簡單的評論系統,主要用於大家分享自己心中的感悟、經驗、心得、想法等。 好了,不賣關子了,這個項目其實是上班無聊的時候寫的,為什麼要寫這個項目呢?因為我單純的想吐槽一下工作中的不滿而已。 項目介紹 項目很簡單,主要功能就是提供一個簡單的評論系統 ...