信息的组织和提取方法

XML:eXtensible Markup Language
<name>...</name>

<name />

<!-- -->
JSON:JavaScript Object Notation
"key":"value"
"key":["value1","value2"]
"key":{"subkey":"subvalue"}
YAML:YAML Ain't Markup Language

key:value

key:#Comment
-value1
-value2

key:
    subkey:subvalue
比较
名称 描述 作用域
XML 最早的通用信息标记语言,可扩展性好,但繁琐。 Internet上的信息交互与传递。
JSON 信息有类型,适合程序处理(js),较XML简洁。 移动应用云端和节点的信息通信,无注释。
YAML 信息无类型,文本信息比例 最高,可读性好。 各类系统的配置文件,有注释易读。

 信息提取的一般方法

<>.find_all(name,attrs,recursive,string,**kwargs)
<tag>(..)等价于<tag>.find_all(..)
soup(..)等价于soup.find_all(..)

示例:

url='http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'

<tbody class="hidden_zhpm" style="text-align: center;">
 <tr class="alt">
  <td>
   1
  </td>
  <td>
   <div align="left">
    清华大学
   </div>
  </td>
  <td>
   北京
  </td>
  <td>
   94.6
  </td>
  <td class="hidden-xs need-hidden indicator5">
   100.0
  </td>
  <td class="hidden-xs need-hidden indicator6" style="display: none;">
   98.30%
  </td>
  <td class="hidden-xs need-hidden indicator7" style="display: none;">
   1589319
  </td>
  <td class="hidden-xs need-hidden indicator8" style="display: none;">
   48698
  </td>
  <td class="hidden-xs need-hidden indicator9" style="display: none;">
   1.512
  </td>
  <td class="hidden-xs need-hidden indicator10" style="display: none;">
   1810
  </td>
  <td class="hidden-xs need-hidden indicator11" style="display: none;">
   126
  </td>
  <td class="hidden-xs need-hidden indicator12" style="display: none;">
   1697330
  </td>
  <td class="hidden-xs need-hidden indicator13" style="display: none;">
   302898
  </td>
  <td class="hidden-xs need-hidden indicator14" style="display: none;">
   6.81%
  </td>
 </tr>
</tbody>

Process finished with exit code 0

1.功能描述:
输入:大学排名url链接
输出:大学排名信息的屏幕输出(排名,大学名称,总分)
技术路线:requests+bs4
定向爬虫:仅对输入URL进行爬取,不扩展爬取。

程序的结构设计
步骤一 从网络上获取大学排名网页内容 getHTMLText()
步骤二 提取网页内容中信息到核实的数据结构 fillUnivList()
步骤三 利用数据结构展示并输出结果 printUnivList()

2.结构框架:

import requests
from bs4 import BeautifulSoup

def getHTMLText(url):
    return ""

def fillUnivList(ulist,html):
    pass

def printUnivList(ulist,num):
    print("Suc" + str(num))

def main():
    unifo = []
    url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html'
    html = getHTMLText(url)
    fillUnivList(unifo,html)
    printUnivList(unifo,20) # 20 univs
main()

填充功能函数getHTMLText():

def getHTMLText(url):
    try:
        r = requests.get(url,timeout = 30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""

填充功能函数fillUnivList():

描述:分析html代码后,根据查找关键词“清华大学”,可知每所大学信息都在<tbody>标签中,然后遍历<tbody>标签中的<tr>标签

用清华大学举例:

html ='<tbody class="hidden_zhpm" style="text-align: center;">' 
      '<tr class="alt">' 
      '<td>1</td>' 
      '<td><div align="left">清华大学</div></td>' 
      '<td>北京</td>' 
      '<td>94.6</td><td class="hidden-xs need-hidden indicator5">100.0</td>' 
      '<td class="hidden-xs need-hidden indicator6"style="display: none;">98.30%</td>' 
      '<td class="hidden-xs need-hidden indicator7"style="display: none;">1589319</td><td class="hidden-xs need-hidden indicator8"style="display: none;">48698</td>' 
      '<td class="hidden-xs need-hidden indicator9"style="display: none;">1.512</td><td class="hidden-xs need-hidden indicator10"style="display: none;">1810</td>' 
      '<td class="hidden-xs need-hidden indicator11"style="display: none;">126</td><td class="hidden-xs need-hidden indicator12"style="display: none;">1697330</td>' 
      '<td class="hidden-xs need-hidden indicator13"style="display: none;">302898</td><td class="hidden-xs need-hidden indicator14"style="display: none;">6.81%</td>' 
      '</tr></tbody>'  # 为了实现单步骤测试效果,手工添加了</tbody>标签

soup = BeautifulSoup(html,"html.parser")

for tr in soup.find('tbody').children:
    print(tr)

运行结果:

<tr class="alt"><td>1</td><td><div align="left">清华大学</div></td><td>北京</td><td>94.6</td><td class="hidden-xs need-hidden indicator5">100.0</td><td class="hidden-xs need-hidden indicator6" style="display: none;">98.30%</td><td class="hidden-xs need-hidden indicator7" style="display: none;">1589319</td><td class="hidden-xs need-hidden indicator8" style="display: none;">48698</td><td class="hidden-xs need-hidden indicator9" style="display: none;">1.512</td><td class="hidden-xs need-hidden indicator10" style="display: none;">1810</td><td class="hidden-xs need-hidden indicator11" style="display: none;">126</td><td class="hidden-xs need-hidden indicator12" style="display: none;">1697330</td><td class="hidden-xs need-hidden indicator13" style="display: none;">302898</td><td class="hidden-xs need-hidden indicator14" style="display: none;">6.81%</td></tr>

def fillUnivList(ulist,html):
    '''提取HTML中的关键数据,并且填到一个列表中'''
    soup = BeautifulSoup(html, "html.parser")
    for tr in soup.find('tbody').children:
        if isinstance(tr, bs4.element.Tag):  # 检测tr标签类型,如果tr标签不是bs4.element.Tag,将过滤掉,为了使这行代码可以正常运行,需要引入bs4库
            # 在实际标签树构建过程中,每一个标签的儿子标签可能出现字符串类型,这里所有大学信息都封装在<tr>标签中,<tr>标签是Tag类型,这里需要过滤掉非标签类型,所以可以使用isinstance函数做一个判断
            tds = tr('td')
            ulist.append([tds[0].string,tds[1].string,tds[3].string])
def printUnivList(ulist,num):
    print("{:^10}	{:^10}	{:^10}".format("排名","大学名称","得分"))
    for i in range(num):
        u = ulist[i]
        print("{:^10}	{:^10}	{:^10}".format(u[0],u[1],u[2]))

完整代码:

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):
    '''提取HTML中的关键数据,并且填到一个列表中'''
    soup = BeautifulSoup(html, "html.parser")
    for tr in soup.find('tbody').children:
        if isinstance(tr, bs4.element.Tag):  # 检测tr标签类型,如果tr标签不是bs4.element.Tag,将过滤掉,为了使这行代码可以正常运行,需要引入bs4库
            # 在实际标签树构建过程中,每一个标签的儿子标签可能出现字符串类型,这里所有大学信息都封装在<tr>标签中,<tr>标签是Tag类型,这里需要过滤掉非标签类型,所以可以使用isinstance函数做一个判断
            tds = tr('td')
            ulist.append([tds[0].string,tds[1].string,tds[3].string])

def printUnivList(ulist,num):
    print("{:^10}	{:^10}	{:^10}".format("排名","大学名称","得分"))
    for i in range(num):
        u = ulist[i]
        print("{:^10}	{:^10}	{:^10}".format(u[0],u[1],u[2]))

def main():
    unifo = []
    url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html'
    html = getHTMLText(url)
    fillUnivList(unifo,html)
    printUnivList(unifo,20) # 20 univs
main()
    排名           大学名称           得分    
    1            清华大学          94.6   
    2            北京大学          76.5   
    3            浙江大学          72.9   
    4           上海交通大学         72.1   
    5            复旦大学          65.6   
    6          中国科学技术大学        60.9   
    7           华中科技大学         58.9   
    7            南京大学          58.9   
    9            中山大学          58.2   
    10         哈尔滨工业大学         56.7   
    11         北京航空航天大学        56.3   
    12           武汉大学          56.2   
    13           同济大学          55.7   
    14          西安交通大学         55.0   
    15           四川大学          54.4   
    16          北京理工大学         54.0   
    17           东南大学          53.6   
    18           南开大学          52.8   
    19           天津大学          52.3   
    20          华南理工大学         52.0   
Suc20

Process finished with exit code 0

补充:关于输出格式中,中文字符格式对齐问题,以下做了代码调试:

def printUnivList(ulist,num):
    tplt = "{0:^10}	{1:{3}^10}	{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)))
    排名           大学名称           得分    
    1            清华大学          94.6   
    2            北京大学          76.5   
    3            浙江大学          72.9   
    4           上海交通大学         72.1   
    5            复旦大学          65.6   
    6          中国科学技术大学        60.9   
    7           华中科技大学         58.9   
    7            南京大学          58.9   
    9            中山大学          58.2   
    10         哈尔滨工业大学         56.7   
    11         北京航空航天大学        56.3   
    12           武汉大学          56.2   
    13           同济大学          55.7   
    14          西安交通大学         55.0   
    15           四川大学          54.4   
    16          北京理工大学         54.0   
    17           东南大学          53.6   
    18           南开大学          52.8   
    19           天津大学          52.3   
    20          华南理工大学         52.0   
原文地址:https://www.cnblogs.com/leisurelyRD/p/12378329.html