Python按照你的检索爬取天津大学图书馆书籍信息

Python按照你的检索爬取天津大学图书馆书籍信息


完全自己手写的代码,入门级水平把。对于静态HTML网页爬取来说相对简单,现在对于动态编写JavaScript还不知道如何处理。由于天津大学图书馆书籍相关信息都写在静态html中,爬取还是很简单的。

爬取步骤

1.通过requests.get()得到网页内容
2.通过BeautifulSoup类可以对网页进行解析,筛选你所需要的信息或者标签,也可以通过正则表达式获取你所需要的内容。
3.将你获取的信息放入数据结构中,比如jason文件、txt文件、excel文件、mysql文件中,这里我们由于信息少,放入list列表中并打印出来。

网页解析

在这里插入图片描述
打开天大图书馆,输入检索字段python,可以得到上图所示,此处为第一页,后面还有第二页,第三页;首先要清楚网页链接检索含义。

http://opac.lib.tju.edu.cn/opac/search?q=python&searchType=standard&isFacet=true&view=standard&rows=10&sortWay=pubdate_sort&sortOrder=desc&hasholding=1&searchWay0=marc&q0=&logical0=AND&page=1
#其中,检索python字段为连接中q=python,如果检索为matlab,则为q=matlab;页数则为page=1,第二页则为page=2

清楚了网页链接的含义,则需要开一下网页源代码,右键点击打开源代码。

<table class="resultTable">		
				<tr>
					<td width="20px">
						<input type="checkbox" name="bookItemCheckbox" 
							id="bookItem_992598" value="992598" />
					</td>
					<td width="20px">
						1. 
					</td>
					<td class="coverTD"> 
						<a href="javascript:bookDetail(992598,1,0);">
						<img class="bookcover_img" src="/opac/media/images/book-default-small.gif"  
							isbn="9783319963556"  bookrecno="992598"/>
						</a>
					</td>
					<td class="bookmetaTD" style="background-color:#F8F8F8">
						<div class="bookmeta" bookrecno="992598">
							<div>
								<span class="bookmetaTitle">
									<a href="javascript:bookDetail(992598,1,0);" id="title_992598">
										Optimization of Energy Supply Systems: Modelling, Programming and Analysis /
									</a>
									
								</span>
								<a href="javascript:bookDetail(992598,1,1);">
									<img border="0" title="在新窗口显示详细信息" src="/opac/media/images/newwin.png" />
								</a>
								&nbsp;
										<img src="/opac/media/images/rank_1.png" title="匹配度差"/>
									
								
								<span class="biblios_ordering" style="display: none;">
									订购中
								</span>
								<span class="reservation_count" ></span>
								<!-- 湖北省馆 -->	
								<!-- 如果有附件则显示非书资料的图标 -->
								
								<span id="attachment_992598" style="display: none;">
									<font color="green">(含光盘)</font>
								</span>
								
							</div>
							<div>著者:
								<a href="/opac/search?searchWay=author&q=by Janet Nagel." target="_blank"> 
									by Janet Nagel.
								</a>
							</div>
							<div>
								出版社: 
								<a href="/opac/search?searchWay=publisher&q=Springer International Publishing :" target="_blank"> 
									Springer International Publishing :
								</a>
								&nbsp;
								出版日期: 2019.
							</div>
							<div>
								文献类型: 
								<img src="/opac/booktypeicon/6" class="booktypeIcon" />
								外文电子书, 
								索书号:
								<span class="callnosSpan"></span>
							</div>
						</div>
						<div class="expressServiceTab" id="express_tab_992598" 
							express_bookrecno="992598" express_isbn="9783319963556" express_bookmeta_loaded="0">
							<ul>
								<li><a id="holdingPreview_A_992598" href="#holdingPreviewDiv_992598">在馆信息</a></li>
								<li><a href="#bookSimpleDetailDiv_992598">图书信息概览</a></li>
									<li class="hide" id="book_catalog_9783319963556"><a href="#bookCatalog_992598">图书目录</a></li>
									<li class="hide" id="book_preview_9783319963556"><a href="#bookPreview_992598">试读信息</a></li>	
									<li class="hide" id="book_summary_9783319963556"><a href="#bookContentSummary_992598">内容简介</a></li>
									<li class="hide" id="book_authorIntroduction_9783319963556"><a href="#bookAuthorIntroduction_992598">著者简介</a></li>		
							</ul>
							<!--iframe id="holdingPreviewIFrame_992598" width="100%" frameborder="0">
							</iframe-->
							<div id="holdingPreviewDiv_992598" inittimes="0">
							</div>
							<div id="bookSimpleDetailDiv_992598">
								<iframe id="bookSimpleDetailIFrame_992598" width="100%" frameborder="0">
								</iframe>
							</div>	
								<div id="bookCatalog_992598"></div>
								<div id="bookPreview_992598"></div>
								<div id="bookContentSummary_992598"></div>
								<div id="bookAuthorIntroduction_992598"></div>	
						</div>
					</td>
				</tr>
.........................................此处省略n行
</table>

以上可以卡看出,所有书籍信息均放在< table>总标签中,每一本书的信息又放在< tr>子标签中,一层一层分析,找出书籍名称,作者以及出处信息所在的标签。

代码

import requests
from bs4 import BeautifulSoup

def getHTMLText(url):
    try:
        r = requests.get(url,timeout=10)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        print('获取网页异常!')
def HTML2List(list,html):
    soup = BeautifulSoup(html,'html.parser')
    for t in soup.findAll('td',attrs = {'class':'bookmetaTD'}):
        tds = t.find_all('a')
        book_name = tds[0].string.strip()
        ausor_name = tds[2].string.strip()
        chubanshe_name = tds[3].string.strip()
        list.append([book_name,ausor_name,chubanshe_name])
def printList(list):
    print('{:^20}{:^20}{:^20}'.format('书名','作者','出版社'))
    for i in range(len(list)):
        print('{:^20}{:^20}{:^20}'.format(list[i][0],list[i][1],list[i][2]))

def main():
    name = 'python'
    page = 2
    list = []
    for i in range(page):
        url = 'http://opac.lib.tju.edu.cn/opac/search?q=' + name +'&searchType=standard&isFacet=true&view=standard&rows=10&sortWay=pubdate_sort&sortOrder=desc&hasholding=1&searchWay0=marc&q0=&logical0=AND&page=' + str(i+1)
        html =getHTMLText(url)
        HTML2List(list,html)
        printList(list)
if __name__ == '__main__':
    main()

运行结果:

         书名                  作者                 出版社         
Optimization of Energy Supply Systems: Modelling, Programming and Analysis /  by Janet Nagel.   Springer International Publishing :
Computational Science/Intelligence & Applied Informaticsedited by Roger Lee.Springer International Publishing :
 利用Python开源工具分析恶意代码  () 赵涏元 ... [] 著        人民邮电出版社       
     游戏服务器架构与优化             蔡能著               机械工业出版社       
Elasticsearch大数据搜索引擎        罗刚编著              电子工业出版社       
     Python程序设计          () 约翰·策勒著           人民邮电出版社       
  MicroPython入门指南          邵子扬编著              电子工业出版社       
   Python机器学习基础教程   () Andreas C. Müller, () Sarah Guido著      人民邮电出版社       
   Python物理学高效计算    () 安东尼·斯科普斯, () 凯瑟琳·赫夫著      人民邮电出版社       
   Python数字信号处理应用        () 艾伦·唐尼著           人民邮电出版社       
树莓派实战全攻略:Scratch、Python、Linux、Minecraft应用与机器人智能制作   () 斯图尔特·沃特金斯著         人民邮电出版社       
    BGP路由协议排错指南     () 维尼特·贾恩, () 布拉德·埃奇沃斯著      人民邮电出版社       
 Python与量化投资:从基础到实战        主编王小川等             电子工业出版社       
知识网络与合作网络的关系研究:基于Python编程        张晓黎著               格致出版社        
    虫术:Python绝技             梁睿坤著              电子工业出版社       
 Diana10.1土木工程有限元分析         柴舜编著              南京大学出版社       
Python data science handbook =: Python数据科学手册 / Jake VanderPlas著.        东南大学出版社,      
 零基础学编程:树莓派和Python          金学林著              电子工业出版社       
  从零开始学Python程序设计          吴惠茹等编著             机械工业出版社       
  Python数据分析与数据化运营          宋天龙著              机械工业出版社       

其中还有一些bug,以后再说2333333333

猜你喜欢

转载自blog.csdn.net/weixin_39549161/article/details/86585357