zoukankan      html  css  js  c++  java
  • python&MongoDB爬取图书馆借阅记录(没有验证码)

      题外话:这个爬虫本来是想用java完成然后发布在博客园里的,但是一直用java都失败了,最后看到别人用了python,然后自己就找别人问了问关键的知识点,发现连接那部分,python只用了19行!!!!!好了,其他的就不多说,直接上需求和代码

      首先是需要爬取的链接和网页:http://211.81.31.34/uhtbin/cgisirsi/x/0/0/57/49?user_id=LIBSCI_ENGI&password=LIBSC

      

      登陆进去之后进入我的账号——借阅、预约及申请记录——借阅历史就可以看到所要爬取的内容

      

      然后将借阅历史中的题名、著者、借阅日期、归还日期、索书号存入Mongodb数据库中,以上便是这次爬虫的需求。

    下面开始:

    各软件版本为:

    python 2.7.11

    MongoDb 3.2.1

    Pycharm 5.0.4

    MongoDb Management Studio 1.9.3

    360极速浏览器 懒得查了

    一、登陆模块

    python中的登陆一般都是用urllib和urllib2这两个模块,首先我们要查看网页的源代码:

     1         <form name="loginform" method="post" action="/uhtbin/cgisirsi/?ps=nPdFje4RP9/理工大学馆/125620449/303">
     2 <!--  Copyright (c) 2004, Sirsi Corporation - myProfile login or view myFavorites -->
     3 <!--  Copyright (c) 1998 - 2003, Sirsi Corporation - Sets the default values for USER_ID, ALT_ID, and PIN prompts. - The USER_ID, ALT_ID, and PIN page variables will be returned. -->
     4 
     5 <!-- If the user has not logged in, first try to default to the ID based on the IP address - the $UO and $Uf will be set.  If that fails, then default to the IDs in the config file. If the user has already logged in, default to the logged in user's IDs, unless the user is a shared login. -->
     6 
     7 
     8 
     9       <!-- only user ID is used if both on -->
    10         <div class="user_name">
    11             <label for="user_id">借阅证号码:</label>
    12             <input class="user_name_input" type="text" name="user_id" id="user_id"  maxlength="20" value=""/>
    13         </div>
    14     
    15      
    16         <div class="password">
    17             <label for="password">个人密码:</label>
    18             <input class="password_input" type="password" name="password" id="password"  maxlength="20" value=""/>
    19         </div>  
    20     
    21      
    22     <input type="submit" value="用户登录" class="login_button"/>

    查找网页中的form表单中的action,方法为post,但是随后我们发现,该网页中的action地址不是一定的,是随机变化的,刷新一下就变成了下面这样子的:

    1  <form name="loginform" method="post" action="/uhtbin/cgisirsi/?ps=1Nimt5K1Lt/理工大学馆/202330426/303">

    我们可以看到/?ps到/之间的字符串是随机变化的(加粗部分),于是我们需要用到另一个模块——BeautifulSoup实时获取该链接:

    1         url = "http://211.81.31.34/uhtbin/cgisirsi/x/0/0/57/49?user_id=LIBSCI_ENGI&password=LIBSC"
    2         res = urllib2.urlopen(url).read()
    3         soup = BeautifulSoup(res, "html.parser")
    4         login_url = "http://211.81.31.34" + soup.findAll("form")[1]['action'].encode("utf8")

    之后就可以正常使用urllib和urllib来模拟登陆了,下面列举一下BeautifulSoup的常用方法,之后的HTML解析需要:

    1.soup.contents 该属性可以将tag的子节点以列表的方式输出

    2.soup.children 通过tag的.children生成器,可以对tag的子节点进行循环

    3.soup.parent 获取某个元素的父节点

    4.soup.find_all(name,attrs,recursive,text,**kwargs) 搜索当前tag的所有tag子节点,并判断是否符合过滤器的条件

    5.soup.find_all("a",class="xx") 按CSS搜索

    6.find(name,attrs,recursive,text,**kwargs) 可以通过limit和find_all区分开

    更多资料请访问BeautifulSoup官网:http://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

    二、解析所获得的HTML

    先看看需求中的HTML的特点:

     1      <tbody id="tblSuspensions">
     2 <!-- OCLN changed Listcode to Le to support charge history -->
     3      <!-- SIRSI_List Listcode="LN" -->
     4 
     5      <tr>
     6        <td class="accountstyle" align="left">
     7           <!-- SIRSI_Conditional IF List_DC_Exists="IB" AND NOT List_DC_Comp="IB^" -->
     8 <!-- Start title here -->
     9  <!-- Title -->
    10             做人要低调,说话要幽默 孙郡铠编著
    11         </td>
    12        <td class="accountstyle author" align="left">
    13           <!-- Author -->
    14             孙郡铠 编著
    15         </td>
    16        <td class="accountstyle due_date" align="center">
    17           <!-- Date Charged -->
    18             2015/9/10,16:16
    19        </td>
    20         <td class="accountstyle due_date" align="left">
    21         <!-- Date Returned -->
    22             2015/9/23,15:15
    23         </td>
    24 
    25         <td class="accountstyle author" align="center">
    26           <!-- Call Number -->
    27             B821-49/S65
    28         </td>
    29 
    30       </tr>
    31 
    32      <tr>
    33        <td class="accountstyle" align="left">
    34           <!-- SIRSI_Conditional IF List_DC_Exists="IB" AND NOT List_DC_Comp="IB^" -->
    35 <!-- Start title here -->
    36  <!-- Title -->
    37             我用一生去寻找 潘石屹的人生哲学 潘石屹著
    38         </td>
    39        <td class="accountstyle author" align="left">
    40           <!-- Author -->
    41             潘石屹, 1963- 著
    42         </td>
    43        <td class="accountstyle due_date" align="center">
    44           <!-- Date Charged -->
    45             2015/9/10,16:16
    46        </td>
    47         <td class="accountstyle due_date" align="left">
    48         <!-- Date Returned -->
    49             2015/9/25,15:23
    50         </td>
    51 
    52         <td class="accountstyle author" align="center">
    53           <!-- Call Number -->
    54             B821-49/P89
    55         </td>
    56 
    57       </tr>

    由所有代码,注意这行:

    <tbody id="tblSuspensions">
    该标签表示下面的内容将是借阅书籍的相关信息,我们采用遍历该网页所有子节点的方法获得id="tblSuspensions"的内容:
    1             for i, k in enumerate(BeautifulSoup(detail, "html.parser").find(id='tblSuspensions').children):
    2                 # print i,k
    3                 if isinstance(k, element.Tag):
    4                     bookhtml.append(k)
    5                     # print type(k)

    三、提取所需要的内容

    这一步比较简单,bs4中的BeautifulSoup可以轻易的提取:

     1             for i in bookhtml:
     2                 # p
     3                 # rint i
     4                 name = i.find(class_="accountstyle").getText()
     5                 author = i.find(class_="accountstyle author", align="left").getText()
     6                 Date_Charged = i.find(class_="accountstyle due_date", align="center").getText()
     7                 Date_Returned = i.find(class_="accountstyle due_date", align="left").getText()
     8                 bookid = i.find(class_="accountstyle author", align="center").getText()
     9                 bookinfo.append(
    10                     [name.strip(), author.strip(), Date_Charged.strip(), Date_Returned.strip(), bookid.strip()])
    这一步采用getText()的方法将text中内容提取出来;strip()方法是去掉前后空格,同时可以保留之间的空格,比如:s="   a a  ",使用s.strip()之后即为"a a"

    四、连接数据库
    据说NoSQL以后会很流行,随后采用了Mongodb数据库图图新鲜,结果一折腾真是烦,具体安装方法在上一篇日记中记载了。
    1.导入python连接Mongodb的模块
      import pymongo
    2.创建python和Mongodb的链接:
    1 # connection database
    2 conn = pymongo.MongoClient("mongodb://root:root@localhost:27017")
    3 db = conn.book
    4 collection = db.book

    3.将获得的内容保存到数据库:

    1                 user = {"_id": xuehao_ben,
    2                         "Bookname": name.strip(),
    3                         "Author": author.strip(),
    4                         "Rent_Day": Date_Charged.strip(),
    5                         "Return_Day": Date_Returned.strip()}
    6                 j += 1
    7                 collection.insert(user)

    上面基本完成了,但是爬虫做到这个没有意义,重点在下面

    五、获取全校学生的借阅记录

      我们学校的图书馆的密码都是一样的,应该没有人闲得无聊改密码,甚至没有人用过这个网站去查询自己的借阅记录,所以,做个循环,就可以轻易的获取到全校的借阅记录了,然后并没有那么简单,str(0001)强制将int变成string,但是在cmd的python中是报错的(在1位置),在pycharm前面三个0是忽略的,只能用傻瓜式的四个for循环了。好了,下面是所有代码:

      1 # encoding=utf8
      2 import urllib2
      3 import urllib
      4 import pymongo
      5 import socket
      6 
      7 from bs4 import BeautifulSoup
      8 from bs4 import element
      9 
     10 # connection database
     11 conn = pymongo.MongoClient("mongodb://root:root@localhost:27017")
     12 db = conn.book
     13 collection = db.book
     14 
     15 
     16 # 循环开始
     17 def xunhuan(xuehao):
     18     try:
     19         socket.setdefaulttimeout(60)
     20         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     21         s.bind(("127.0.0.1", 80))
     22         url = "http://211.81.31.34/uhtbin/cgisirsi/x/0/0/57/49?user_id=LIBSCI_ENGI&password=LIBSC"
     23         res = urllib2.urlopen(url).read()
     24         soup = BeautifulSoup(res, "html.parser")
     25         login_url = "http://211.81.31.34" + soup.findAll("form")[1]['action'].encode("utf8")
     26         params = {
     27             "user_id": "账号前缀你猜你猜" + xuehao,
     28             "password": "密码你猜猜"
     29         }
     30         print params
     31         params = urllib.urlencode(params)
     32         req = urllib2.Request(login_url, params)
     33         lianjie = urllib2.urlopen(req)
     34         # print lianjie
     35         jieyue_res = lianjie.read()
     36         # print jieyue_res     首页的HTML代码
     37         houmian = BeautifulSoup(jieyue_res, "html.parser").find_all('a', class_='rootbar')[1]['href']
     38         # print houmian
     39         houmian = urllib.quote(houmian.encode('utf8'))
     40         url_myaccount = "http://211.81.31.34" + houmian
     41         # print url_myaccount
     42         # print urllib.urlencode(BeautifulSoup(jieyue_res, "html.parser").find_all('a',class_ = 'rootbar')[0]['href'])
     43 
     44         lianjie2 = urllib.urlopen(url_myaccount)
     45         myaccounthtml = lianjie2.read()
     46         detail_url = ''
     47         # print (BeautifulSoup(myaccounthtml).find_all('ul',class_='gatelist_table')[0]).children
     48         print "连接完成,开始爬取数据"
     49         for i in (BeautifulSoup(myaccounthtml, "html.parser").find_all('ul', class_='gatelist_table')[0]).children:
     50             if isinstance(i, element.NavigableString):
     51                 continue
     52             for ii in i.children:
     53                 detail_url = ii['href']
     54             break
     55         detail_url = "http://211.81.31.34" + urllib.quote(detail_url.encode('utf8'))
     56         detail = urllib.urlopen(detail_url).read()
     57         # print detail
     58         bookhtml = []
     59         bookinfo = []
     60 
     61         # 解决没有借书
     62         try:
     63             for i, k in enumerate(BeautifulSoup(detail, "html.parser").find(id='tblSuspensions').children):
     64                 # print i,k
     65                 if isinstance(k, element.Tag):
     66                     bookhtml.append(k)
     67                     # print type(k)
     68             print "look here!!!"
     69             j = 1
     70             for i in bookhtml:
     71                 # p
     72                 # rint i
     73                 name = i.find(class_="accountstyle").getText()
     74                 author = i.find(class_="accountstyle author", align="left").getText()
     75                 Date_Charged = i.find(class_="accountstyle due_date", align="center").getText()
     76                 Date_Returned = i.find(class_="accountstyle due_date", align="left").getText()
     77                 bookid = i.find(class_="accountstyle author", align="center").getText()
     78                 bookinfo.append(
     79                     [name.strip(), author.strip(), Date_Charged.strip(), Date_Returned.strip(), bookid.strip()])
     80                 xuehao_ben = str(xuehao) + str("_") + str(j)
     81                 user = {"_id": xuehao_ben,
     82                         "Bookname": name.strip(),
     83                         "Author": author.strip(),
     84                         "Rent_Day": Date_Charged.strip(),
     85                         "Return_Day": Date_Returned.strip()}
     86                 j += 1
     87                 collection.insert(user)
     88         except Exception, ee:
     89             print ee
     90             print "此人没有借过书"
     91             user = {"_id": xuehao,
     92                     "Bookname": "此人",
     93                     "Author": "没有",
     94                     "Rent_Day": "借过",
     95                     "Return_Day": ""}
     96             collection.insert(user)
     97 
     98         print "********" + str(xuehao) + "_Finish"+"**********"
     99     except Exception, e:
    100         s.close()
    101         print e
    102         print "socket超时,重新运行"
    103         xunhuan(xuehao)
    104 
    105 
    106 # with contextlib.closing(urllib.urlopen(req)) as A:
    107 #    print A
    108 #   print xuehao
    109 # print req
    110 
    111 for i1 in range(0, 6):
    112     for i2 in range(0, 9):
    113         for i3 in range(0, 9):
    114             for i4 in range(0, 9):
    115                 xueha = str(i1) + str(i2) + str(i3) + str(i4)
    116                 chushi = '0000'
    117                 if chushi == xueha:
    118                     print "=======爬虫开始=========="
    119                 else:
    120                     print xueha + "begin"
    121                     xunhuan(xueha)
    122 
    123 conn.close()
    124 print "End!!!"

    下面是Mongodb Management Studio的显示内容(部分):





      总结:这次爬虫遇到了很多问题,问了很多人,但是最终效果还不是很理想,虽然用了try except语句,但是还是会报错10060,连接超时(我只能质疑学校的服务器了TT),还有就是,你可以看到数据库中列的顺序不一样=。=这个我暂时未理解,求各位博客园友解释了(づ ̄ 3 ̄)づ,感谢那些这次爬取帮过我的人(*^__^*),再接再厉,加油↖(^ω^)↗

  • 相关阅读:
    Silverlight4实现三维企业网站
    (学)Lazarus 字符串压缩、解压缩
    (原)Oracel 函数返回 Decimal 丢失小数位问题
    (原)如何提高软件运行速度
    (转) ORA01033: ORACLE 正在初始化或关闭
    (学)正在写一个陌生行业的方案,努力ing
    (学)Telerik GridFoot 如何加合计
    (思)爱的路上千万里
    (学)Telerik RadGridView 中Column 数据字段绑定
    写在2011年伊始
  • 原文地址:https://www.cnblogs.com/w1570631036/p/5182633.html
Copyright © 2011-2022 走看看