四小时学python爬虫爬取信息系列(第二天)

四小时学python爬虫爬取信息系列(第二天)(全是干货)
今天目的就是用一个定向爬虫爬取中国大学2020年排名,爬取之前请先查看robot协议。

1.安装Beautiful Soup库(可以在电脑python,我是进入anaconda我建的虚拟环境)

Beautiful Soup库是解析、遍历、维护“标签书”的功能库。

anaconda虚拟环境法流程:

conda activate py36         //进入我的py36环境
pip install beautifulsoup4 -i https://pypi.tuna.tsinghua.edu.cn/simple   //安装requests库 

电脑python流程:直接cmd,输入下面命令,可能会提示你升级pip ,可以升级

#如果需要升级pip输入:python -m pip install --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install beautifulsoup4 -i https://pypi.tuna.tsinghua.edu.cn/simple  //安装beautifulsoup4库 

2.验证安装(直接在命令行python或者在python idle进行输入)

import requests
r=requests.get("http://python123.io/ws/demo.html")
r.text

输出:

'<html><head><title>This is a python demo page</title></head>\r\n<body>\r\n<p class="title"><b>The demo python introduces several python courses.</b></p>\r\n<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>\r\n</body></html>'

把输出存到一个变量demo里面

demo=r.text
from bs4 import BeautifulSoup
soup=BeautifulSoup(demo,"html.parser")
print(soup.prettify())

输出:(证明beautiful soup库安装好了)(这就是一棵“标签树”)

<html>
 <head>
  <title>
   This is a python demo page
  </title>
 </head>
 <body>
  <p class="title">
   <b>
    The demo python introduces several python courses.
   </b>
  </p>
  <p class="course">
   Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
   <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
    Basic Python
   </a>
   and
   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
    Advanced Python
   </a>
   .
  </p>
 </body>
</html>

整理:(调用beautiful soup库方法)

from bs4 import BeautifulSoup
soup=BeautifulSoup('<p>data</p>',"html.parser")

2.解析Beautiful Soup库

<p>..</p>:标签Tag
<p class="title">...</p>
#其中p为名称,成对出现;中间的class=“title”为属性域(>=0个属性)
HTML<->标签书<->BeautifulSoup类

实例:

from bs4 import BeautifulSoup
soup=BeautifulSoup("<html>data</html>","html.parser")
soup2=BeautifulSoup(open("D://demo.html"),"html.parser")
#bs4的HTML解析器    BeautifulSoup(mk,'html.parser')  
pip install beautifulsoup4 -i https://pypi.tuna.tsinghua.edu.cn/simple   //安装bs4库 

#lxml的HTML解析器   BeautifulSoup(mk,'lxml')    
pip install lxml -i https://pypi.tuna.tsinghua.edu.cn/simple   //安装lxml库 

#lxml的XML解析器    BeautifulSoup(mk,'xml')
pip install lxml -i https://pypi.tuna.tsinghua.edu.cn/simple   //安装lxml库 

#html5lib解析器     BeautifulSoup(mk,'html5lib')
pip install html5lib -i https://pypi.tuna.tsinghua.edu.cn/simple   //安装html5lib库 

Beautiful Soup类

Tag                  #标签,<>和</>表示开头和结尾
Name                 #标签名字p,<p>...</p>,<tag>.name
Attributes           #标签属性,字典形式,<tag>.attrs
NavigableString      #标签内非属性字符串,<>...</>中的字符串,<tag>.string
Comment              #标签内字符串的注释部分,特殊的Comment类型

实例:

import requests
from bs4 import BeautifulSoup
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
soup=BeautifulSoup(demo,"html.parser")
soup.title   #output  <title>This is a python demo page</title>
tag=soup.a
print(tag)   #return a标签
#output <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>

整理:

import requests
from bs4 import BeautifulSoup
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
soup=BeautifulSoup(demo,"html.parser")
#Name
soup.a.name                   #output:  'a'
soup.a.parent.name            #output:  'p'
soup.a.parent.parent.name     #output:  'body'
#Attributes 
tag=soup.a
tag.attrs                     
#output:{'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}
tag.attrs['id']               #output:  'link1'
tag.attrs['class']            #output:  ['py1']
tag.attrs['href']             #output:  'http://www.icourse163.org/course/BIT-268001'
type(tag.attrs)               #output:  <class 'dict'>
type(tag)                     #output:  <class 'bs4.element.Tag'>
#NavigableString
soup.p.string                 #output:  'The demo python introduces several python courses.'
type(soup.p.string)           #output:  <class 'bs4.element.NavigableString'>
#Comment
soup2=BeautifulSoup("<b><!--This is a comment--></b><p>This is not a comment</p>","html.parser")
type(soup2.b.string)          #output:  <class 'bs4.element.Comment'>
type(soup2.p.string)          #output:  <class 'bs4.element.NavigableString'>

3.关于标签树的三种遍历

1)下行遍历

.contents       #子节点的列表,将<tag>所有子节点存入列表
.children       #子节点迭代类型,与.contents类似,用于循环遍历儿子结点
.descendants    #子孙节点迭代类型,包含所有子孙节点,用于循环遍历

代码:

import requests
from bs4 import BeautifulSoup
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
soup=BeautifulSoup(demo,"html.parser")
soup.head
soup.head.contents
len(soup.head.contents)   #1
len(soup.body.contents)   #5
soup.body.contents[1]     #取第一个孩子节点

2)上行遍历

.parent    #节点的父亲标签
.parents   #节点的先辈标签的迭代类型,用于循环遍历先辈节点

代码:

import requests
from bs4 import BeautifulSoup
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
soup=BeautifulSoup(demo,"html.parser")
soup.title.parent

print上层标签

import requests
from bs4 import BeautifulSoup
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
soup=BeautifulSoup(demo,"html.parser")
for parent in soup.a.parents:
	if parent is None:
		print(parent)
	else:
		print(parent.name)

效果截图:

在这里插入图片描述

3)平行遍历(同一父亲节点)

.next_sibling           #return按照HTML文本顺序的下一个平行节点标签
.previous_sibling       #return按照HTML文本顺序的上一个平行节点标签
.next_siblings          #迭代类型,按照HTML文本顺序的后续所有平行节点标签
.previous_siblings      #迭代类型,按照HTML文本顺序的前续所有平行节点标签

代码:

import requests
from bs4 import BeautifulSoup
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
soup=BeautifulSoup(demo,"html.parser")
print(soup.a.next_sibling)   #and
print(soup.a.next_sibling.next_sibling)
#output:<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
print(soup.a.previous_sibling)
#output:Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking
#遍历后续节点
for sibling in soup.a.next_siblings:
	print(sibling)
#遍历前续节点
for sibling in soup.a.previous_siblings:
	print(sibling)
  1. bs4库的prettify()来美化代码
import requests
from bs4 import BeautifulSoup
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
soup=BeautifulSoup(demo,"html.parser")
print(soup.prettify())
#还可单独取出其中一个标签,例如取出a标签
soup.a.prettify()

输出:(这样美化的代码更加方便阅读)(本质就是给html文本增加了‘\n’换行符)

<html>
 <head>
  <title>
   This is a python demo page
  </title>
 </head>
 <body>
  <p class="title">
   <b>
    The demo python introduces several python courses.
   </b>
  </p>
  <p class="course">
   Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
   <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
    Basic Python
   </a>
   and
   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
    Advanced Python
   </a>
   .
  </p>
 </body>
</html>

5.信息的标记,XML是由HTML发展而来

(三种:XML类似于HTML,JSON有类型键值对[]或{}嵌套,YAML无类型键值对缩进表示,'-‘表并列,’|‘表标记,’#'表注释)

例如csdn的主页用的就是XML,图片如下:

在这里插入图片描述

6.信息的提取(形式解析+搜索)

import requests
from bs4 import BeautifulSoup
r=requests.get("http://python123.io/ws/demo.html")
demo=r.text
soup=BeautifulSoup(demo,"html.parser")
for link in soup.find_all('a'):
	print(link.get('href'))

输出:

http://www.icourse163.org/course/BIT-268001
http://www.icourse163.org/course/BIT-1001870001

7.基于bs4库的HTML内容查找方法

<>.find_all(name,attrs,recursive,string,**kwargs)
#return一个列表类型,存储查找的结果
#name:对标签名的检索字符串
#查找a标签
soup.find_all('a')

#查找a和b标签
soup.find_all(['a','b'])

#查找所有的标签
for tag in soup.find_all(Ture):
	print(tag.name)

#查找以b开头的标签
import re
for tag in soup.find_all(re.compile('b')):
	print(tag.name)
#attrs:标签属性值的检索字符串,可标注属性标签
soup.find_all('p','course')
soup.find_all(id='link1')

#查找link字段,引入正则表达式
import re
soup.find_all(id=re.compile('link'))
#recursive:bool类型,是否对子孙全部检索,默认True
soup.find_all('a',recursive=False)
#string:<>...</>中字符串区域的检索字符串
soup.find_all(string="Basic Python")

#正则表达式解锁'python'
import re
soup.find_all(string=re.compile("python"))
<tag>(...)等价<tag>.find_all(...)
soup(...) 等价 soup.find_all(...)

扩展方法:

<>.find                           #搜索只返回一个结果,字符串类型,同.find_all()参数
<>.find_parents()                 #在先辈节点中搜索,return列表类型,同.find_all()参数
<>.find_parent()                  #在先辈节点中return一个结果,字符串类型,同.find()参数
<>.find_next_siblings()           #在后续平行节点中搜索,return列表类型,同.find_all()参数
<>.find_next_sibling()            #在后续平行节点中return一个结果,字符串类型,同.find()参数
<>.find_previous_siblings()       #在前序平行节点中搜索,return列表类型,同.find_all()参数
<>.find_previous_sibling()        #在前序平行节点中return一个结果,字符串类型,同.find()参数

8.爬取2020年全国大学排名显示前50名(定向爬虫)

程序需求分析:

1.输入:大学排名URL链接

2.输出:大学排名信息(排名,大学名称,省份)
代码:

import requests
from bs4 import BeautifulSoup
import bs4
def getHTMLText(url):
	try:
		r=requests.get(url,timeout=30)
		r.raise_for_status() #200则正常,非200返回requsets.HTTPError
		r.encoding=r.apparent_encoding
		return r.text
	except:
		return""
def fillUnivList(ulist, html):
	soup=BeautifulSoup(html,"html.parser")
	for tr in soup.find('tbody').children:
		if isinstance(tr,bs4.element.Tag):
			tds=tr('td')
			ulist.append([tds[0].string,tds[1].string,tds[2].string])
def printUnivList(ulist, num):
	tplt="{0:^20}\t{1:{3}^10}\t{2:^10}"
	print(tplt.format("排名","学校名称","省份",chr(12288)))
	for i in range(num):
		u=ulist[i]
		print(tplt.format(u[0],u[1],u[2],chr(12288)))
if __name__== "__main__":
	uinfo=[]
	url="http://www.zuihaodaxue.cn/zuihaodaxuepaiming2020.html"
	html=getHTMLText(url)
	fillUnivList(uinfo, html)
	printUnivList(uinfo, 50)

输出:

D:\ProgramData\Anaconda3\envs\py36\python.exe D:/program/python/pc.py
         排名         	   学校名称   	    省份    
         1          	   清华大学   	    北京    
         2          	   北京大学   	    北京    
         3          	   浙江大学   	    浙江    
         4          	  上海交通大学  	    上海    
         5          	   南京大学   	    江苏    
         6          	   复旦大学   	    上海    
         7          	 中国科学技术大学 	    安徽    
         8          	  华中科技大学  	    湖北    
         9          	   武汉大学   	    湖北    
         10         	   中山大学   	    广东    
         11         	  西安交通大学  	    陕西    
         12         	 哈尔滨工业大学  	   黑龙江    
         13         	 北京航空航天大学 	    北京    
         14         	  北京师范大学  	    北京    
         15         	   同济大学   	    上海    
         16         	   四川大学   	    四川    
         17         	   东南大学   	    江苏    
         18         	  中国人民大学  	    北京    
         19         	   南开大学   	    天津    
         20         	  北京理工大学  	    北京    
         21         	   天津大学   	    天津    
         22         	   山东大学   	    山东    
         23         	   厦门大学   	    福建    
         24         	   吉林大学   	    吉林    
         25         	  华南理工大学  	    广东    
         26         	   中南大学   	    湖南    
         27         	  大连理工大学  	    辽宁    
         28         	  西北工业大学  	    陕西    
         29         	  华东师范大学  	    上海    
         30         	  中国农业大学  	    北京    
         31         	   湖南大学   	    湖南    
         32         	  电子科技大学  	    四川    
         33         	  北京科技大学  	    北京    
         34         	   重庆大学   	    重庆    
         35         	 南京航空航天大学 	    江苏    
         36         	  南京理工大学  	    江苏    
         37         	   东北大学   	    辽宁    
         38         	   苏州大学   	    江苏    
         39         	  华中农业大学  	    湖北    
         40         	   兰州大学   	    甘肃    
         41         	 西安电子科技大学 	    陕西    
         42         	  华东理工大学  	    上海    
         43         	  北京交通大学  	    北京    
         44         	  华中师范大学  	    湖北    
         45         	   上海大学   	    上海    
         46         	  南方科技大学  	    广东    
         47         	  南京农业大学  	    江苏    
         48         	   暨南大学   	    广东    
         49         	  中国海洋大学  	    山东    
         50         	  南京师范大学  	    江苏    

进程已结束,退出代码 0

效果截图:
在这里插入图片描述爬爬爬第二天结束,收工,,,,,,明天继续,欢迎关注,如果我的博客对你有帮助请点个赞吧

  • 10
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

visual_eagle

欢迎交流学习

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值