第二周学习笔记之二

信息标记的三种形式

XML

(eXtensible Markup Language)
格式:<img src=“china.jpg” size=“10”> … </img>
空元素的缩写形式:<img src=“china.jpg” size=“10” />
注释书写形式: <!‐‐ This is a comment, very useful ‐‐>

JSON

(JavsScript Object Notation)
有类型的键值对key:value
“key” : “value”
“key” : [“value1”, “value2”]
“key” : {“subkey” : “subvalue”}

YAML

(YAML Ain’t Markup Language)
无类型键值对key:value
缩进表达所属关系
表达并列关系:
name :
‐北京理工大学
‐延安自然科学院
| 表达整块数据
# 表示注释
key : value
key : #Comment
‐value1
‐value2
key :
subkey : subvalue

三种方法的比较

XML : 最早的通用信息标记语言,可扩展性好,但繁琐
JSON: 信息有类型,适合程序处理(js),较XML简洁(甚至可直接作为Java代码的一部分)
YAML: 信息无类型,文本信息比例最高,可读性好

用途

XML: Internet上的信息交互与传递
JSON: 移动应用云端和节点的信息通信,无注释
YAML: 各类系统的配置文件,有注释易读

信息提取的一般方法

方法一:完整解析信息的标记形式,再提取关键信息

需要标记解析器,例如:bs4库的标签树遍历
优点: 信息解析准确
缺点: 提取过程繁琐,速度慢

方法二:无视标记形式,直接搜索关键信息

对信息的文本查找函数即可
优点: 提取过程简洁,速度较快
缺点: 提取结果准确性与信息内容相关

融合方法

融合方法: 结合形式解析与搜索方法,提取关键信息

实例

交互代码
首先是demo

'))
>>> import requests
>>> r=requests.get("http://python123.io/ws/demo.html")
>>> demo=r.text
>>> demo
'<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>'

检索HTML的所有url链接
思路: 1) 搜索到所<a>标签
2) 解析<a>标签格式,提取href后的链接内容

>>> from bs4 import BeautifulSoup
>>> 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

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

find_all方法

find_all (name, attrs, recursive, string, **kwargs)
返回一个列表类型,存储查找的结果

name : 对标签名称的检索字符串

例子

>>> soup.find_all('a')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all(['a','b'])
[<b>The demo python introduces several python courses.</b>, <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> for tag in soup.find_all(True):
	print(tag.name)
html
head
title
body
p
b
p
a
a
>>> for tag in soup.find_all(True):
	print(tag)

这种检索需要检索信息完整且准确,故之后会学习到正则表达式进行关键词检索

>>> import re
>>> for tag in soup.find_all(re.compile('b')):
	print(tag.name)

body
b
attrs: 对标签属性值的检索字符串,可标注属性检索
>>> soup.find_all('p','course')
[<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>]
>>> soup.find_all(id='link1')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>]
>>> soup.find_all(id='link')
[]
>>> import re
>>> soup.find_all(id=re.compile('link'))
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
recursive: 是否对子孙全部检索,默认True
>>> soup.find_all(id=re.compile('link'))
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all('a')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all('a',recursive=False)
[]
string: <>…</>中字符串区域的检索字符串
>>> 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>
>>> soup.find_all(string='Basic Python')
['Basic Python']
>>> import re
>>> soup.find_all(string=re.compile('python'))
['This is a python demo page', 'The demo python introduces several python courses.']

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

拓展方法

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

中国大学排名获取实例

实现一

#CrawUnivRankingA.py import  requests
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[3].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.cn/zuihaodaxuepaiming2016.html' 
    html  =  getHTMLText(url)
    fillUnivList(uinfo,  html) 
    printUnivList(uinfo,  20)  #  20  univs
main()

在这里插入图片描述
输出的结果却不对齐,原因是当空格不够时。默认填充的是西文字符的空格。

代码优化

所以以下实现对于打印函数的优化

def  printUnivList(ulist,  num):
    tplt="{0:^10}\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)))

在这里插入图片描述

小结: 理解了有关HTML中的格式以及内容,进行了爬虫的实例操作以及有了一定认识,正则表达式的内容比较令自己期待。
同时对于格式化,居中处理是第一次见。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值