zoukankan      html  css  js  c++  java
  • 中国大学MOOC —— 学习笔记(二)

    注:本文仅是个人的学习笔记,内容来源于中国大学mooc《Python网络爬虫与信息提取》课程

    一 信息标记与提取方法

    信息标记三种方式:

    XML    <>...</>

    JSON  有类型键值对:key:value

    YAML  无类型键值对:key:value

    信息提取的一般方法:

    <>.find_all()

    <tag>(...)等价于<tag>.find_all(...)

    soup(...)等价于soup.find_all(...)

    二 中国大学排名定向爬取

    Google 浏览器审查元素时按Ctrl + f 可以调出搜索框。

    目标链接:http://www.zuihaodaxue.com/zuihaodaxuepaiming2017.html

    功能描述:

    输入大学的url,输出大学信息。

    定向爬虫:仅对输入url进行爬虫,不扩展爬取。

    代码演示:

    import requests
    import bs4
    from bs4 import BeautifulSoup
    
    def getHtmlText(url):
         try:
              r = requests.get(url)
              """
              如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),
              我们可以通过Response.raise_for_status() 来抛出异常
              
              """
              r.raise_for_status()
              r.encoding = r.apparent_encoding         
              return r.text
         except:
              return " "
    
    def fillUnivList(ulist,html):
         soup = BeautifulSoup(html,'lxml')#注1
         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[3].string])
    
    def printUnivList(ulist,num):
         print("{:^10}	{:^6}	{:^10}".format("排名","学校名称","总分"))#注2
         for i in range(num):
              u = ulist[i]
              print("{:^10}	{:^6}	{:^10}".format(u[0],u[1],u[2]))
              
    def main():
         uinfo = []
         url = "http://www.zuihaodaxue.cn/zuihaodaxuepaiming2017.html"
         html = getHtmlText(url)
         fillUnivList(uinfo,html)
         printUnivList(uinfo,20)
    main()

    注1:解析器之间的区别

    注2:python中format用法

    printUnivList函数优化后的代码:

    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)))

    三 中文对齐的方法

  • 相关阅读:
    HDU1852 Beijing 2008(快速幂+特殊公式)
    HihoCoder 1570 : 小Hi与法阵(简单几何)
    【转】反素数
    【整理】线段树30题
    SPOJcot2 Count on a tree II (树上莫队)
    【总结】曼哈顿距离转切比雪夫距离
    【初识】树上分块
    基于Tablestore Tunnel的数据复制实战
    【New Feature】阿里云快照服务技术解析
    基于日志服务的GrowthHacking(1):数据埋点和采集(APP、Web、邮件、短信、二维码埋点技术)
  • 原文地址:https://www.cnblogs.com/BeautifulSoup/p/8452868.html
Copyright © 2011-2022 走看看