python爬取西北大学就业信息网并且按宣讲顺序排序

参考了http://blog.csdn.net/pleasecallmewhy/article/details/8934726

 西北大学就业信息网如下:

         就业信息是按发布日期排序,而不是按宣讲日期排序。如果我想知道11月10日有哪些招聘单位,还要每页的翻看,而已有可能漏掉,简直太不人性化。

         所以我就把所有的就业信息给爬取了出来,并且按照宣讲顺序进行了排序。

         主要思路:  按下F12,查看源代码,查找出所有的标题:字符串1 ,再从标题中查找出日期:字符串2,再找出所有的发布日期:字符串3。输出结果=字符串1+字符串2+字符串3.

例如第一个标题:

 

所以对应的程序为:

    # 获取页面源码并将其存储到数组中
    def get_data(self, url, endPage):
            url = url + '&page='
            for i in range(1, endPage + 1):
                print u'爬虫报告:正在爬取第%d页...' % i
                myPage = urllib2.urlopen(url + str(i)).read()
                myItems = re.findall('news_show.aspx.*?>(.*?)<', myPage.decode('utf-8'), re.S)

                send_times = re.findall('adding-right.*?>(.*?)<a', myPage.decode('utf-8'), re.S)
                for item in myItems:
                    data = self.myTool.Replace_Char(item.replace("", "").encode('utf-8'))
                    self.datas.append(data)

                for times in send_times:
                    data_times = self.myTool.Replace_Char(times.replace("", "").encode('utf-8'))
                    self.data_timeS.append('  '+data_times + '\n' + '\n')

爬取10页数据,程序运行状态截图:

      

爬取结果输出的txt如下:

      

全部代码如下(因为用的别处的DEMO,所以可能有不相关的地方):           

# coding=UTF-8
# -*- coding: utf-8 -*-
# ---------------------------------------
#   程序:西北大学就业信息网
#   版本:0.1
#   作者:LZX
#   日期:2016-10-28
#   语言:Python 2.7
#   操作:输入网址后自动只看楼主并保存到本地文件
#   功能:将楼主发布的内容打包txt存储到本地。
# ---------------------------------------

import string
import urllib2
import re
nian=['月'];
yue=['日  '];
st=[1]*300;
o=['0'];
end_page=int(10);
end_Number=int(end_page*12);
# ----------- 处理页面上的各种标签 -----------
class HTML_Tool:
    # 用非 贪婪模式 匹配 \t 或者 \n 或者 空格 或者 超链接 或者 图片
    BgnCharToNoneRex = re.compile("(\t|\n| |<a.*?>|<img.*?>)")

    # 用非 贪婪模式 匹配 任意<>标签
    EndCharToNoneRex = re.compile("<.*?>")

    # 用非 贪婪模式 匹配 任意<p>标签
    BgnPartRex = re.compile("<p.*?>")
    CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)")
    CharToNextTabRex = re.compile("<td>")

    # 将一些html的符号实体转变为原始符号
    replaceTab = [("<", "<"), (">", ">"), ("&", "&"), ("&", "\""), (" ", " ")]

    def Replace_Char(self, x):
        x = self.BgnCharToNoneRex.sub("", x)
        x = self.BgnPartRex.sub("\n    ", x)
        x = self.CharToNewLineRex.sub("\n", x)
        x = self.CharToNextTabRex.sub("\t", x)
        x = self.EndCharToNoneRex.sub("", x)

        for t in self.replaceTab:
            x = x.replace(t[0], t[1])
        return x


class Baidu_Spider:
    # 申明相关的属性
    def __init__(self, url):
        self.myUrl = url
        self.datas = []
        self.data_timeS = []
        self.myTool = HTML_Tool()
        print u'已经启动爬虫,咔嚓咔嚓'

    # 初始化加载页面并将其转码储存
    def baidu_tieba(self):
        # 读取页面的原始信息并将其从gbk转码
        myPage = urllib2.urlopen(self.myUrl).read().decode('utf-8')
        # 计算楼主发布内容一共有多少页
        endPage = self.page_counter(myPage)
        # 获取该帖的标题
        title = self.find_title(myPage)
        print u'文章名称:' + title
        # 获取最终的数据
        self.save_data(self.myUrl, title, endPage)

    # 用来计算一共有多少页
    def page_counter(self, myPage):
        # 匹配 "共有<span class="red">12</span>页" 来获取一共有多少页
        myMatch = re.search(r'class="red">(\d+?)</span>', myPage, re.S)
        if myMatch:
            endPage = end_page
            print u'爬虫报告:发现楼主共有%d页的原创内容' %endPage
        else:
            endPage = end_page
            print u'爬虫报告:爬取前10页数据!'
        return endPage

    # 用来寻找该帖的标题
    def find_title(self, myPage):
        # 匹配 <h1 class="core_title_txt" title="">xxxxxxxxxx</h1> 找出标题
        myMatch = re.search(r'<h1.*?>(.*?)</h1>', myPage, re.S)
        title = u'校园招聘'
        if myMatch:
            title = 22
        else:
            print u'爬虫报告:无法加载文章标题!'
        # 文件名不能包含以下字符: \ / : * ? " < > |
        title = title.replace('\\', '').replace('/', '').replace(':', '').replace('*', '').replace('?', '').replace('"',
                                                                                                                    '').replace(
            '>', '').replace('<', '').replace('|', '')
        return title

        # 用来存储楼主发布的内容

    # 将内容从页面代码中抠出来
        #def deal_data(self, myPage):

    # 获取页面源码并将其存储到数组中
    def get_data(self, url, endPage):
            url = url + '&page='
            for i in range(1, endPage + 1):
                print u'爬虫报告:正在爬取第%d页...' % i
                myPage = urllib2.urlopen(url + str(i)).read()
                myItems = re.findall('news_show.aspx.*?>(.*?)<', myPage.decode('utf-8'), re.S)

                send_times = re.findall('adding-right.*?>(.*?)<a', myPage.decode('utf-8'), re.S)
                for item in myItems:
                    data = self.myTool.Replace_Char(item.replace("", "").encode('utf-8'))
                    self.datas.append(data)

                for times in send_times:
                    data_times = self.myTool.Replace_Char(times.replace("", "").encode('utf-8'))
                    self.data_timeS.append('  '+data_times + '\n' + '\n')

                # 将myPage中的html代码处理并存储到datas里面
                # self.deal_data(myPage.decode('utf-8'))

    def save_data(self, url, title, endPage):
                # 加载页面数据到数组中
                self.get_data(url, endPage)
                # 打开本地文件
                f = open(title + '.txt', 'w+')
                for i in range(0, end_Number):
                    time = re.findall(r'\d+', self.datas[i])

                    if int(time[0])<10:
                        time[0]=o[0]+time[0]
                    if int(time[1])<10:
                        time[1]=o[0]+time[1]

                    st[i] = time[0]+nian[0]+ time[1]+yue[0]
                    self.datas[i] = st[i]+ self.datas[i]+self.data_timeS[i]
                for i in range(0, end_Number-2):
                    for j in range(0, end_Number-1):
                        if st[j] <= st[j + 1]:
                            zj_str = self.datas[j]
                            zj_time = st[j]

                            st[j] = st[j + 1]
                            self.datas[j] = self.datas[j + 1]

                            st[j + 1] = zj_time
                            self.datas[j + 1] = zj_str
                f.writelines(self.datas)
                f.close()
                print u'爬虫报告:文件已下载到本地并打包成txt文件'
                print u'请按任意键退出...'
                raw_input();
# -------- 程序入口处 ------------------
print u"""#---------------------------------------
#   程序:西北大学就业信息网
#   版本:0.1
#   作者:lzx
#   日期:2016-10-28
#   语言:Python 2.7
#   操作:输入网址后自动只看楼主并保存到本地文件
#   功能:将楼主发布的内容打包txt存储到本地。
#---------------------------------------
"""

# 以某小说贴吧为例子
# bdurl = http://jiuye.nwu.edu.cn/website/news_list.aspx?category_id=46

print u'请输入ok开始爬虫:'
if raw_input()=='ok':
    bdurl = 'http://jiuye.nwu.edu.cn/website/news_list.aspx?category_id=46'


# 调用
mySpider = Baidu_Spider(bdurl)
mySpider.baidu_tieba()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值