位置: 编程技术 - 正文

python&MongoDB爬取图书馆借阅记录(mongodb python)

编辑:rootadmin

推荐整理分享python&MongoDB爬取图书馆借阅记录(mongodb python),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:python操作mongodb数据库,python爬取数据存入mongodb,python操作mongodb数据库,mongodb orm python,mongodb 爬虫,mongo python,python读取mongodb数据,mongodb python,内容如对您有帮助,希望把文章链接给更多的朋友!

直接上需求和代码首先是需要爬取的链接和网页:  

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

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

下面开始:

各软件版本为:

python 2.7. MongoDb 3.2.1 Pycharm 5.0.4 MongoDb Management Studio 1.9.3 极速浏览器 懒得查了

一、登陆模块python中的登陆一般都是用urllib和urllib2这两个模块,首先我们要查看网页的源代码:<form name="loginform" method="post" action="/uhtbin/cgisirsi/&#;ps=nPdFje4RP9/理工大学馆//"><!-- Copyright (c) , Sirsi Corporation - myProfile login or view myFavorites --><!-- Copyright (c) - , 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. -->

<!-- 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. -->

<!-- only user ID is used if both on --> <div class="user_name"> <label for="user_id">借阅证号码:</label> <input class="user_name_input" type="text" name="user_id" id="user_id" maxlength="" value=""/> </div> <div class="password"> <label for="password">个人密码:</label> <input class="password_input" type="password" name="password" id="password" maxlength="" value=""/> </div> <input type="submit" value="用户登录" class="login_button"/>查找网页中的form表单中的action,方法为post,但是随后我们发现,该网页中的action地址不是一定的,是随机变化的,刷新一下就变成了下面这样子的: <form name="loginform" method="post" action="/uhtbin/cgisirsi/&#;ps=1Nimt5K1Lt/理工大学馆//">我们可以看到/&#;ps到/之间的字符串是随机变化的(加粗部分),于是我们需要用到另一个模块——BeautifulSoup实时获取该链接:url = " res = urllib2.urlopen(url).read() soup = BeautifulSoup(res, "html.parser")login_url = " + 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区分开

二、解析所获得的HTML

先看看需求中的HTML的特点:<tbody id="tblSuspensions"><!-- OCLN changed Listcode to Le to support charge history --> <!-- SIRSI_List Listcode="LN" -->

python&MongoDB爬取图书馆借阅记录(mongodb python)

<tr> <td class="accountstyle" align="left"> <!-- SIRSI_Conditional IF List_DC_Exists="IB" AND NOT List_DC_Comp="IB^" --><!-- Start title here --> <!-- Title --> 做人要低调,说话要幽默 孙郡铠编著 </td> <td class="accountstyle author" align="left"> <!-- Author --> 孙郡铠 编著 </td> <td class="accountstyle due_date" align="center"> <!-- Date Charged --> /9/,: </td> <td class="accountstyle due_date" align="left"> <!-- Date Returned --> /9/,: </td>

<td class="accountstyle author" align="center"> <!-- Call Number --> B-/S </td>

</tr>

<tr> <td class="accountstyle" align="left"> <!-- SIRSI_Conditional IF List_DC_Exists="IB" AND NOT List_DC_Comp="IB^" --><!-- Start title here --> <!-- Title --> 我用一生去寻找 潘石屹的人生哲学 潘石屹著 </td> <td class="accountstyle author" align="left"> <!-- Author --> 潘石屹, - 著 </td> <td class="accountstyle due_date" align="center"> <!-- Date Charged --> /9/,: </td> <td class="accountstyle due_date" align="left"> <!-- Date Returned --> /9/,: </td>

<td class="accountstyle author" align="center"> <!-- Call Number --> B-/P </td>

</tr>由所有代码,注意这行:

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

这一步比较简单,bs4中的BeautifulSoup可以轻易的提取:for i in bookhtml: # p # rint i name = i.find(class_="accountstyle").getText() author = i.find(class_="accountstyle author", align="left").getText() Date_Charged = i.find(class_="accountstyle due_date", align="center").getText() Date_Returned = i.find(class_="accountstyle due_date", align="left").getText() bookid = i.find(class_="accountstyle author", align="center").getText() bookinfo.append( [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 pymongo2.创建python和Mongodb的链接:# connection databaseconn = pymongo.MongoClient(" = conn.bookcollection = db.book3.将获得的内容保存到数据库:user = {"_id": xuehao_ben, "Bookname": name.strip(), "Author": author.strip(), "Rent_Day": Date_Charged.strip(), "Return_Day": Date_Returned.strip()} j += 1 collection.insert(user)上面基本完成了,但是爬虫做到这个没有意义,重点在下面

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

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

from bs4 import BeautifulSoupfrom bs4 import element

# connection databaseconn = pymongo.MongoClient(" = conn.bookcollection = db.book

# 循环开始def xunhuan(xuehao): try: socket.setdefaulttimeout() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((".0.0.1", )) url = " res = urllib2.urlopen(url).read() soup = BeautifulSoup(res, "html.parser") login_url = " + soup.findAll("form")[1]['action'].encode("utf8") params = { "user_id": "账号前缀你猜你猜" + xuehao, "password": "密码你猜猜" } print params params = urllib.urlencode(params) req = urllib2.Request(login_url, params) lianjie = urllib2.urlopen(req) # print lianjie jieyue_res = lianjie.read() # print jieyue_res 首页的HTML代码 houmian = BeautifulSoup(jieyue_res, "html.parser").find_all('a', class_='rootbar')[1]['href'] # print houmian houmian = urllib.quote(houmian.encode('utf8')) url_myaccount = " + houmian # print url_myaccount # print urllib.urlencode(BeautifulSoup(jieyue_res, "html.parser").find_all('a',class_ = 'rootbar')[0]['href'])

lianjie2 = urllib.urlopen(url_myaccount) myaccounthtml = lianjie2.read() detail_url = '' # print (BeautifulSoup(myaccounthtml).find_all('ul',class_='gatelist_table')[0]).children print "连接完成,开始爬取数据" for i in (BeautifulSoup(myaccounthtml, "html.parser").find_all('ul', class_='gatelist_table')[0]).children: if isinstance(i, element.NavigableString): continue for ii in i.children: detail_url = ii['href'] break detail_url = " + urllib.quote(detail_url.encode('utf8')) detail = urllib.urlopen(detail_url).read() # print detail bookhtml = [] bookinfo = []

# 解决没有借书 try: for i, k in enumerate(BeautifulSoup(detail, "html.parser").find(id='tblSuspensions').children): # print i,k if isinstance(k, element.Tag): bookhtml.append(k) # print type(k) print "look here!!!" j = 1 for i in bookhtml: # p # rint i name = i.find(class_="accountstyle").getText() author = i.find(class_="accountstyle author", align="left").getText() Date_Charged = i.find(class_="accountstyle due_date", align="center").getText() Date_Returned = i.find(class_="accountstyle due_date", align="left").getText() bookid = i.find(class_="accountstyle author", align="center").getText() bookinfo.append( [name.strip(), author.strip(), Date_Charged.strip(), Date_Returned.strip(), bookid.strip()]) xuehao_ben = str(xuehao) + str("_") + str(j) user = {"_id": xuehao_ben, "Bookname": name.strip(), "Author": author.strip(), "Rent_Day": Date_Charged.strip(), "Return_Day": Date_Returned.strip()} j += 1 collection.insert(user) except Exception, ee: print ee print "此人没有借过书" user = {"_id": xuehao, "Bookname": "此人", "Author": "没有", "Rent_Day": "借过", "Return_Day": "书"} collection.insert(user)

print "********" + str(xuehao) + "_Finish"+"**********" except Exception, e: s.close() print e print "socket超时,重新运行" xunhuan(xuehao)

# with contextlib.closing(urllib.urlopen(req)) as A:# print A# print xuehao# print req

for i1 in range(0, 6): for i2 in range(0, 9): for i3 in range(0, 9): for i4 in range(0, 9): xueha = str(i1) + str(i2) + str(i3) + str(i4) chushi = '' if chushi == xueha: print "=======爬虫开始==========" else: print xueha + "begin" xunhuan(xueha)

conn.close()print "End!!!"下面是Mongodb Management Studio的显示内容(部分):

  总结:这次爬虫遇到了很多问题,问了很多人,但是最终效果还不是很理想,虽然用了try except语句,但是还是会报错,连接超时(我只能质疑学校的服务器了TT),还有就是,你可以看到数据库中列的顺序不一样=。=这个我暂时未理解,希望大家可以给出解决方法。

标签: mongodb python

本文链接地址:https://www.jiuchutong.com/biancheng/382330.html 转载请保留说明!

上一篇:Python中常用操作字符串的函数与方法总结(python常用操作运算符)

下一篇:深入讲解Java编程中类的生命周期(java编程基础知识入门)

  • 建筑企业差额征税如何开票
  • 代收的水资源税收入是否计入企业所得税
  • 计提税金是什么会计科目
  • 营业外支出增加的原因
  • 退回资本金要交税吗
  • 公务员工资待遇标准表
  • 住房补贴是不是编制才有
  • 投资性房地产房产税应按从价还是从租
  • 一般纳税人增值税申报操作流程
  • 上级拨付的固定资产增加类型是什么
  • 水利建设专项收入怎么报税
  • 银行提供服务收费标准
  • 无形资产研究费用计入成本么
  • 企业法人不是实际老板怎么办
  • 盘盈固定资产冲销啥科目
  • 出口企业享受增值税优惠政策
  • 员工的家庭
  • 税收折旧率
  • 仓储费用的增值税计入哪里
  • 个人生产经营所得
  • 城市生活垃圾处理费应该交吗
  • 税友服务费能否抵扣
  • 以后年度继续扣除广告宣传费,要怎么写分录?
  • 电商销售进对公账户怎样做账
  • 小规模减半征收什么时候开始
  • 滴滴开的发票能否抵扣进项税
  • 所得税招待费用
  • win7系统ie浏览器在哪里
  • 增值税开票系统客服电话
  • 小企业会计准则和一般企业会计准则的区别
  • win11任务栏全部显示
  • linux -e -f
  • 民间非营利组织会计账务处理
  • 高新企业研发费用会计分录
  • 本月未抵扣完的进项税是否转出
  • 什么是减值测试方法
  • WordPress导航菜单权限控制
  • 野生动物保护区有哪些
  • 房地产取得土地怎么做账
  • 老生常谈PHP 文件写入和读取(必看篇)
  • framework core
  • 核定征收印花税的文件
  • vue导出word文档打开报错,内容有问题
  • 融资租入的办公楼
  • php链表的应用场景
  • 一行简单的代码
  • torch.cuda.is_available()
  • python0基础
  • 法人可以开个人票会怎么样
  • 总公司签协议,分公司开票,报账怎样写说明
  • sql数据库移动
  • mongodb查询工具
  • 劳务成本 科目
  • 企业的专利年费是多少
  • 股东的投资款怎么收回
  • sql server2014教程
  • 财务报表没报会影响出口退税吗为什么
  • 咨询服务业优惠政策
  • 政府补贴专项资金补贴开发票
  • 过户车子需要带什么证件
  • 公司多出来的钱怎么办
  • 暂扣员工工资应怎么处理
  • 支付银行手续费等直接收费金融服务
  • 跨年取得的发票
  • mysql无法配置
  • mac怎么安装新系统
  • vc6_cn_full.exe
  • Win10系统怎样把Word转成PDF
  • 如何在苹果电脑上下载软件
  • linux怎么用u盘传输文件
  • win10系统日历怎么放在桌面
  • 简述js和jquery的关系
  • javascript函数调用函数
  • js数组entries
  • jquery查找指定元素
  • 增值税发票税控开票软件客服
  • 销售钢材的税率增值税税率是多少
  • 新公司税务登记完后还需要什么流程
  • 怎么查询12345的验证码
  • 实名办税有什么作用
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设