1. 程式人生 > >scrapy爬蟲的幾個案例

scrapy爬蟲的幾個案例

lz最近在學習scrapy爬蟲框架,對於此框架,我自己用兩個案例進行了實踐,初步對這個框架掌握,就寫一篇部落格來記錄下我的學習過程。

一、我的環境

mac+python2.7.6+scrapy1.4.0版本。對於scrapy在mac中的安裝過程就不做介紹了。

二、爬取清華大學就業資訊網的就業資訊板塊就業資訊

清華大學就業資訊網網址:

http://career.tsinghua.edu.cn/,具體爬取招聘資訊板塊內容,網址為:http://career.cic.tsinghua.edu.cn/xsglxt/f/jyxt/anony/xxfb

首先是分析此網頁資訊,需要把其中的每一條就業資訊爬下來,在具體的html中可以通過一些標籤來完善。具體的標籤為/div[@class='content teacher']/div[2]/ul[@class='list'],在這個標籤的路徑下,我們可以進行提取。因為這一頁中具體有10幾條資料,所以需要用for迴圈來輸出即可。但是因為這個招聘資訊有好幾頁,所以需要進行輪詢查詢相關的頁面並提取相關的頁面資訊進行提取。關於具體取哪個頁面,這個引數是放在post提交陣列的form_data的pgno欄位。

具體的scrapy程式碼如下所示:

# -*- coding: utf-8 -*-

import re
import json
import datetime

from scrapy.selector import Selector
import scrapy.spiders
from scrapy.utils.response import get_base_url
from tsinghua.items import TsinghuaItem
import urlparse
from scrapy.utils.url import urljoin_rfc
import datetime,time
import codecs
import smtplib
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from scrapy.mail import MailSender
from email.utils import parseaddr,formataddr
from email.header import Header
from email.mime.base import MIMEBase
from email import encoders
import os

class TsinghuaSpider(scrapy.spiders.Spider):
    name = "tsinghua"
    allowed_domains = ["tsinghua.edu.cn"]
    items   = []
    max = 0
    today = datetime.date.today()
    #yesterday = today - datetime.timedelta(days=1)
    '''
    start_urls = [
        "http://career.cic.tsinghua.edu.cn/xsglxt/f/jyxt/anony/xxfb"
    ]
    '''
    URL = "http://career.cic.tsinghua.edu.cn/xsglxt/f/jyxt/anony/xxfb"
    offset = 1
    def start_requests(self):
        url = self.URL
        yield scrapy.FormRequest(
            url = self.URL,
            formdata={"pgno":str(self.offset)},
            callback=self.parse
        )

    def parse(self,response):

        sel = Selector(response)
        base_url = get_base_url(response)
        for sss in sel.xpath("//li[@class='clearfix']"):
            item = TsinghuaItem()
            dd = sss.xpath('span/text()').extract()[0]
            d = str(dd)
            t = str(self.today)
            #篩選了一下就業資訊的時間,只挑選當日釋出的就業資訊
            if t != d:
                print "today %s" %self.today + "   " + "datetime %s" %dd
                continue

            item['Time'] = dd
            item['name'] = sss.xpath("a/text()").extract()[0]
            re_url = sss.xpath("a/@ahref").extract()[0]
            item['detailLink'] = urlparse.urljoin(base_url,re_url)

            #self.items.append(item)
            yield item
            #max = sel.xpath("//b[@id='totalPg']/text()").extract()[0]

        if self.offset < 2:
            self.offset += 1
            print self.offset
            yield scrapy.FormRequest(url = self.URL,formdata={"pgno":str(self.offset)},callback=self.parse)

        #return items





    def closed(self,reason):
        print os.path.getsize(r'/Users/sunwangdong/desktop/tsinghua/tsinghua_%s.json'%self.today)
        if (os.path.getsize(r'/Users/sunwangdong/desktop/tsinghua/tsinghua_%s.json'%self.today) == 0):
            os.remove(r'/Users/sunwangdong/desktop/tsinghua/tsinghua_%s.json'%self.today)
        '''
        data = []
        with open('/Users/sunwangdong/desktop/tsinghua/tsinghua.json') as f:
            for line in f:
                data.append(json.loads(line))

        file_object = codecs.open('tsinghua.txt','w',"utf-8")
        str = "\r\n"
        splitstr = "#___#"
        for item in data:
            str = "%s#___#%s#___#%s\r\n" % (item['name'],item['detailLink'],item['Time'].strip())
            file_object.write(str)
        '''

        sender = ''    
        receiver = ['']     #郵箱地址
        #subject = u'gift for u'
        smtpserver = 'smtp.163.com'
        username = ''
        password = ''    #163郵箱的附件碼

        msgRoot = MIMEMultipart()
        msgRoot['Subject'] = Header('就業資訊 %s' %self.today,'utf-8').encode()
        name,addr = parseaddr('朋友 <%s>' % sender)
        msgRoot['From'] = formataddr((Header(name,'utf-8').encode(),addr)).encode()
        msgRoot['To'] = ','.join(receiver)




        filename = r'/Users/sunwangdong/desktop/tsinghua/tsinghua_%s.txt'%self.today
        if os.path.exists(filename):
            msgRoot.attach(MIMEText('This is my gift!', 'plain', 'utf-8'))
            att = MIMEText(open('tsinghua.txt','rb').read(),'base64','utf-8')
            att["Content-Type"] = 'application/octet-stream'
            att["Content-Disposition"] = 'attachment; filename="tsinghua_%s.txt"'%self.today
            msgRoot.attach(att)

            '''
            with open('/Users/sunwangdong/desktop/tsinghua/tsinghua.txt','r') as f:
                mime = MIMEBase('text','txt',filename='tsinghua.txt')
                mime.set_payload(f.read())
                encoders.encode_base64(mime)
                msgRoot.attach(mime)
            
            
            att = MIMEText(open('/Users/sunwangdong/desktop/tsinghua/tsinghua.json','r').read(),'base64','utf-8')
            att["Content-Type"] = 'application/octet-stream'
            att["Content-Disposition"] = 'attachment; filename="tsinghua.json"'
            '''

            smtp = smtplib.SMTP()
            smtp.connect('smtp.163.com',25)
            smtp.login(username,password)
            smtp.sendmail(sender,receiver,msgRoot.as_string())
            smtp.quit()




            '''
            mailer = MailSender(
                smtphost="smtp.163.com",
                mailfrom="",
                smtpuser="",
                smtppass="",
                smtpport = 25
            )
            body=u'This is the gift for you!'
            subject = u'就業資訊'
            file_name = open('tsinghua.json','r')
            mailer.send(to=["
[email protected]
"],subject=subject.encode('utf-8'),body=body.encode('utf-8'),attachs=(('tsinghua.json','text/plain',))) ''' else: msgRoot.attach(MIMEText('Sorry!Today has no infomation about jobs!', 'plain', 'utf-8')) smtp = smtplib.SMTP() smtp.connect('smtp.163.com', 25) smtp.login(username, password) smtp.sendmail(sender, receiver, msgRoot.as_string()) smtp.quit()

上述程式碼中,我在最後添加了將爬取結果傳送到指定郵箱的操作,而且是生成附件的方式來發送響應的郵件。那麼在pipelines.py檔案中,是用來指定將爬取到的資料通過pipeline檔案以管道的形式傳輸到相應的item檔案中。

class JsonTsinghuaPipeline(object):
      def __init__(self):
            self.file = codecs.open('','a',encoding='utf-8')
      def process_item(self,item,spider):
            line = json.dumps(dict(item),ensure_ascii=False) +"\n"
            self.file.write(line)
            return item
      def spider_closed(self,spider):
            self.file.close()

class TsinghuaPipeline(object):
      def process_item(self,item,spider):
            while open(filename,'a') as f:
                 f.write(item['name'] + '\n')
                 f.write(item['detaillink'] + '\n')
                 f.write(item['Time'] + '\n')
            return item
還有就是items.py檔案,用於描述資料相應的格式
class TsinghuaItem(scrapy.Item):
    name =Field()
    detaillink = Field()
    Time = Field()
將相應的爬取到的資料放置到items生成的新的表格中去。

通過以上方式就可以爬取到清華大學就業資訊網的招聘資訊的內容到某個檔案中,併發送給相應的郵箱中。

相關推薦

scrapy爬蟲案例

lz最近在學習scrapy爬蟲框架,對於此框架,我自己用兩個案例進行了實踐,初步對這個框架掌握,就寫一篇部落格來記錄下我的學習過程。 一、我的環境 mac+python2.7.6+scrapy1.4.0版本。對於scrapy在mac中的安裝過程就不做介紹了。 二、爬取清華大

Scrapy 爬蟲框架入門案例詳解

tin mon setting 爬蟲框架 finished perror project 原因 create 歡迎大家關註騰訊雲技術社區-博客園官方主頁,我們將持續在博客園為大家推薦技術精品文章哦~ 作者:崔慶才 Scrapy入門 本篇會通過介紹一

第八天,scrapy小技巧

一次 load 動態 content btn ajax加載 select efi def 一. 微博模擬登陸 1. 百度搜微博開放平臺可滿足爬取量不大的情況 2. 微博模擬登陸和下拉鼠標應對ajax加載 from selenium import webdriver

風火程式設計--python爬蟲xpath解析方法

python爬蟲解析xpath requests獲取的響應體 from lxml import etree html = etree.HTML(response.text) # 二進位制型別用.content result = html.xpath(“expression”),

Scrapy 爬蟲 --四步驟--

課程設計要用到爬蟲,稍微回顧下,Scrapy的爬蟲四步走....只是簡單的Scrapy,什麼分散式爬蟲啥的,感覺以後再說了....不談了... 1、建立專案 cmd >> scrapy  startproject  douban##

【 MATLAB 】使用 residuez 函式求 z 反變換的案例分析

這篇博文屬於我的專欄:數字訊號處理的MATLAB實現裡面的內容,專欄中給出了這一系列博文的集合,有興趣的可以關注下。 上篇博文講解了 residuez 函式的基礎知識: 這篇博文就給出幾個案例來練練手。 案例1: 為了校核留數計算,考慮下面的有理函式: 使用

ElasticSearch+Solr案例筆記

(一) 最大能索引字串的長度 關於能索引最大的字串長度,其實在Elasticsearch和Solr中都是由底層的Lucene決定的 (1)不分詞+索引的字串最大長度為32766位元組 (2)分詞+索引一般不會出現長度越界問題 (3)不索引的字串雖然沒有長度最大限制

爬蟲-簡單的小檔案

本週第一次接觸爬蟲,在https://scrapy-chs.readthedocs.io/zh_CN/latest/intro/tutorial.html上簡單入門後便在馬神的指導下寫了一些簡單的爬蟲。 因為以前web,html,css,xpath都沒有接觸過

簡單的案例,對動態新增HTML進行了效能比較(包括innerHTML)

    在網上查閱了不少關於innerHTML的效能比較,一直只是間接的得到結果,今天就自己動手寫了下非常簡單的幾個動態新增HTML方法的效能比較,當然,這其中的有許多考慮不周的地方,純粹是為了比較執行時間,並沒有考慮記憶體等資源的消耗,算不上真正的效能比較!下次有時間,進行個完整的效能測試,包括CPU,記

opengl立方體繪制案例

arc ips 立方體 box rman kobject struct round board VC6 下載 http://blog.csdn.net/bcbobo21cn/article/details/44200205 opengl環境配置 htt

Python爬蟲Scrapy(二)_入門案例

efi with 進入 中繼 reload tle 下載 摘要 excel打開 本章將從案例開始介紹python scrapy框架,更多內容請參考:python學習指南 入門案例 學習目標 創建一個Scrapy項目 定義提取的結構化數據(Item) 編寫爬取網站的S

8最高效的Python爬蟲框架,你用過

python 爬蟲 入門 詳細 官網 小編收集了一些較為高效的Python爬蟲框架。分享給大家。1.ScrapyScrapy是一個為了爬取網站數據,提取結構性數據而編寫的應用框架。 可以應用在包括數據挖掘,信息處理或存儲歷史數據等一系列的程序中。。用這個框架可以輕松爬下來如亞馬遜商品信息之

Python小案例,愛上Python編程!

ESS 內容 案例 sta 想象 win32 c99 編程語言 api Python是一種面向對象的解釋型編程語言,源代碼與解釋器CPython遵守GPL協議,Python語法簡潔清晰。 語法簡潔清晰,那麽我們用少量的Python代碼能做哪些有趣的東西?溫馨提示:文末必看。

Python爬蟲入門級別的三案例教程

貼吧爬取 寫程式碼前,構思需要的功能塊;寫程式碼時,把各個功能模組名提前寫好 初始化 初始化必要引數,完成基礎設定 爬取百度貼吧lol吧:爬取地址中的get引數須傳遞(可以指定不同主題的貼吧和頁碼) 主題名 初始網址 請求頭 生成網址 生成每一頁的

JavaWeb基礎總結之Js經典的小案例

 (1)動態顯示當前系統時間 <body> <p>當前時間:<span id="times"></span></p> </body> <script> function get(){

乾貨|爬蟲被封的常見原因

爬蟲採集成為很多公司企業個人的需求,但正因為如此,反爬蟲的技術也層出不窮,像時間限制、IP限制、驗證碼限制等等,都可能會導致爬蟲無法進行,所以也出現了很多像代理IP、時間限制調整這樣的方法去接觸反爬蟲限制,當然具體的操作方法需要你針對性的去研究。 爬蟲採集資料過程中經常會出現受限問題,那麼具

防止爬蟲被反常見策略

動態設定User-Agent(隨機切換User-Agent,模擬不同使用者的瀏覽器資訊) 禁用Cookies(也就是不啟用cookies middleware,不向Server傳送cookies,有些網站通過cookie的使用發現爬蟲行為) 可以通過COOKIES

這八爬蟲框架是目前最牛逼的!你用過哪呢?

小編收集了一些較為高效的Python爬蟲框架。分享給大家。 1.Scrapy Scrapy是一個為了爬取網站資料,提取結構性資料而編寫的應用框架。 可以應用在包括資料探勘,資訊處理或儲存歷史資料等一系列的程式中。。用這個框架可以輕鬆爬下來如亞馬遜商品資訊之類的資料。  

給新手推薦實用又適合上手的Python爬蟲專案

1、爬取網站美圖 爬取圖片是最常見的爬蟲入門專案,不復雜卻能很好地熟悉Python語法、掌握爬蟲思路。 加python學習交流qun 784758214 各種Python新手專案資料包免費領取,不定時還有web、爬蟲等技術的免費知識分享直播教學 當然有兩個點要注意: 不要侵犯版權,要注意營養

給新手推薦實用又適合上手的Python爬蟲項目

9.png htm 推薦 resp 語法 網頁 ges 怎麽 代碼 1、爬取網站美圖 爬取圖片是最常見的爬蟲入門項目,不復雜卻能很好地熟悉Python語法、掌握爬蟲思路。 加python學習交流qun 784758214 各種Python新手項目資料包免費領取,不定時