网络爬虫之提取

Beautiful Soup 库的安装

下载安装完成后即可

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

Beautiful Soup 库的基本元素

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






>>> 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=r.text
>>> from bs4 import BeautifulSoup
>>> soup=BeautifulSoup(demo,"html.parser")
>>> print(soup.prettify())
<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>
>>> soup.title
<title>This is a python demo page</title>
>>> tag=soup.a
>>> tag
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
>>> soup.a.name
'a'
>>> soup.a.parent.name
'p'
>>> soup.a.parent.parent.name
'body'
>>> tag.attrs
{'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}
>>> tag.attrs['class']
['py1']
>>> tag.attrs['href']
'http://www.icourse163.org/course/BIT-268001'
>>> type(tag.attrs)
<class 'dict'>
>>> type(tag)
<class 'bs4.element.Tag'>
>>> soup.a.string
'Basic Python'
>>> soup.p
<p class="title"><b>The demo python introduces several python courses.</b></p>
>>> soup.p.string
'The demo python introduces several python courses.'
>>> type(soup.p.string)
<class 'bs4.element.NavigableString'>

基于bs4库的HTML内容遍历方法







平行遍历发生在同一个父节点下的各节点间



基于bs4库的HTML格式化编码

bs4库默认将读入的HTML转换为utf-8编码。
>>> soup=BeautifulSoup("<p>中文</p>","html.parser")
>>> soup.p.string
'中文'
>>> print(soup.p.prettify())
<p>
 中文
</p>

信息标记的三种方式










XML是用一对尖括号、标签表达信息的格式。

JSON是一种有类型的键值对表达信息的格式。

YAML是一种用无类型的键值对表达信息的格式。






信息提取的一般方法







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



正则表达式的库




例 中国大学排名定向爬虫

程序的程序设计:

  • 步骤1:从网络上获取大学排名网页内容——getHTMLText()
  • 步骤2:提取网页内容中信息到合适的数据结构-----fillUnivList()
  • 步骤3:利用数据结构展示并输出结果——printUnivList()
import requests
from bs4 import BeautifulSoup
import bs4

def getHTMLText(url):
    try:
        r=requests.get(url,timeout=30)
        r.raise_for_status()
        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):
    print("{:^10}\t{:^6}\t{:^10}".format("排名","学校名称","总分"))
    for i in range(num):
        u=ulist[i]
        print("{:^10}\t{:^6}\t{:^10}".format(u[0],u[1],u[2]))

def main():
    uinfo=[]
    url='http://www.zuihaodaxue.com/zuihaodaxuepaiming2018.html'
    html=getHTMLText(url)
    fillUnivList(uinfo,html)
    printUnivList(uinfo,20)
              
main()
==== RESTART: C:/Users/diyhoo/AppData/Local/Programs/Python/Python36/1.py ====
    排名    	 学校名称 	    总分    
    1     	 清华大学 	    北京    
    2     	 北京大学 	    北京    
    3     	 浙江大学 	    浙江    
    4     	上海交通大学	    上海    
    5     	 复旦大学 	    上海    
    6     	中国科学技术大学	    安徽    
    7     	 南京大学 	    江苏    
    8     	华中科技大学	    湖北    
    9     	 中山大学 	    广东    
    10    	哈尔滨工业大学	   黑龙江    
    11    	 同济大学 	    上海    
    12    	 武汉大学 	    湖北    
    13    	 东南大学 	    江苏    
    14    	西安交通大学	    陕西    
    15    	北京航空航天大学	    北京    
    16    	 南开大学 	    天津    
    17    	 四川大学 	    四川    
    18    	 天津大学 	    天津    
    19    	华南理工大学	    广东    
    20    	北京师范大学	    北京    

实例优化


对齐优化:

采用中文字符的空格填充char(12288)

import requests
from bs4 import BeautifulSoup
import bs4

def getHTMLText(url):
    try:
        r=requests.get(url,timeout=30)
        r.raise_for_status()
        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:^10}\t{1:{3}^10}\t{2:^10}"#需要填充时使用format的第三个来填充
    print(tplt.format("排名","学校名称","总分",chr(12288)))
    for i in range(num):
        u=ulist[i]
        print(tplt.format(u[0],u[1],u[2],chr(12288)))

def main():
    uinfo=[]
    url='http://www.zuihaodaxue.com/zuihaodaxuepaiming2018.html'
    html=getHTMLText(url)
    fillUnivList(uinfo,html)
    printUnivList(uinfo,20)
              
main()



猜你喜欢

转载自blog.csdn.net/qq_42020563/article/details/80664311
今日推荐