Coursera课程《Using Python to Access Web Data》 密歇根大学

Week4 Programs that Surf the Web

12.3 Unicode Characters and Strings

Representing Simple Strings

使用ASCII码,每个字符都被一个0到256的数字表示来存在8bits的内存里。

使用ord()函数可以查询,指定字符所对应的ASCII码。

  1. >>> print(ord('H'))
  2. 72
  3. >>> print(ord('e'))
  4. 101
  5. >>> print(ord('\n'))
  6. 10

Multi-Byte Characters

unicode是为了解决之前编码只考虑英文字符的问题而出现的,因为以前的ASCII码只使用一个字节来表示字符,所以它最多也只能表示256个字符, 如果只使用英文是够用的,但是事实是世界要发展,所以出现各种字符,那么它就不够用了。于是就出现了许多的编码方式,例如中国就出了GBK编码。 但是这是不适于国家与国家之间的交流的,于是ISO就指定了unicode这个编码标准。

unicode现在通常是使用两个字节来表示一个字符,但是其实它可以被看成一个字符集,它将所有字符都定义了一个唯一的ID,这样网络就能有一个统一的字符表,不再出现之前的需要相互转化的问题。

那么新的问题就是直接使用unicode来表示字符时,它有时候会浪费空间,在编码表中靠前的字符,例如英文字符,它前一字节就是0000,后一字节才是它真正的序号。 于是,在网络传输中,由于网络带宽并没有这么的理想,大家肯定就会嫌弃unicode编码浪费带宽,所以,于1992年创建,由Ken Thompson创建了UTF传输标准,它的全名是Unicode Transformation Format,这个全名就能明白了UTF的意思。

UTF是针对unicode的一种网络传输标准,按照我们通信的人来说,它就是一种针对unicode的编码方式。 它现在有UTF-7UTF-7.5UTF-8UTF-16UTF-32几种格式,当然现在最为流行的就是其中的UTF-8。 它是一种变长的编码方式,这样就能减少网络传输中的数据量,所以在网络传输中,大家都用它。

Two Kinds of Strings in Python

  1. # python 2.7.10
  2. >>> x = '我爱你'
  3. >>> type(x)
  4. <type 'str'>
  5. >>> x = u'我爱你'
  6. >>> type(x)
  7. <type 'unicode'>
  8. # python 3.5.1
  9. >>> x = '我爱你'
  10. >>> type(x)
  11. <class 'str'>
  12. >>> x = u'我爱你'
  13. >>> type(x)
  14. <class 'str'>

Python2 Versus Python3

  1. # Python 2.7.10
  2. >>> x = b'abc'
  3. >>> type(x)
  4. <type 'str'>
  5. >>> x = '我爱你'
  6. >>> type(x)
  7. <type 'str'>
  8. >>> x = u'我爱你'
  9. >>> type(x)
  10. <type 'unicode'>
  11. # Python 3.5.1
  12. >>> x = b'abc'
  13. >>> type(x)
  14. <class 'bytes'>
  15. >>> x = '我爱你'
  16. >>> type(x)
  17. <class 'str'>
  18. >>> x = u'我爱你'
  19. >>> type(x)
  20. <class 'str'>

在python3内部,所有的字符都是unicode编码,unicode与UTF-8并不能直接通用,所有在字符出入的时候就要加上encode()decode()

Python Strings to Bytes

当我们与外部资源通信时,比如说一个网络socket,我们就要发送bytes。所以我们要把Python3的strings来encode

当我们读取外部资源发来的数据时,我们就要把它decode变成strings。

  1. while True:
  2. data = mysock.recv(512)
  3. if (len(data) < 1):
  4. break
  5. mystring = data.decode()
  6. print(mystring)

也就是说,在网络上大家用bytes(它包含UTF-8等)交流,而在自己的程序里使用unicode

12.4 Retrieving Web Pages

Using urllib in Python

由于HTTP现在太普遍了,所以我们有一个库可以做所有的socket工作,以及让网页看起来像文件一样。

  1. import urllib.request, urllib.parse, urllib.error
  2. fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
  3. for line in fhand:
  4. print(line.decode().strip())

这个urllib.request.urlopen()函数看起来就跟打开文件一样。

Reading Web Pages

  1. import urllib.request,urllib.parse,urllib.error
  2. fhand = urllib.request.urlopen('http://www.dr-chuck.com/page1.htm')
  3. for line in fhand:
  4. print(line.decode().strip())

输出结果

  1. <h1>The First Page</h1>
  2. <p>If you like, you can switch to the <ahref="http://www.dr-chuck.com/page2.htm">Second Page</a>
  3. </p>

其实读取html文件是一样的。

12.5 Parsing Web Pages

What is Web Scraping?

网络数据采集。使用搜索引擎来采集网页数据,我们叫"spidering the web"或者"web crawling"

The Easy Way - Beautiful Soup

BeautifulSoup是一个额外的模块,可以使用pip来安装。

  1. pip install bs4

具体的用处,官方解释如下

Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。

Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。

Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。

  1. import urllib.request,urllib.parse,urllib.error
  2. from bs4 import BeautifulSoup
  3. url = input('Enter -')
  4. html = urllib.request.urlopen(url).read()
  5. soup = BeautifulSoup(html, 'html.parser')
  6. # Retrieve all of the anchor tags
  7. tags = soup('a')
  8. for tag in tags:
  9. print(tag.get('href',None))

其中第6行soup = BeautifulSoup(html, 'html.parser')代码,就是把我们的html文件处理成了一个soup对象.

第9行tags = soup('a')是把html文件中的anchor tag读成了一个anchor tag的list。

第11行的tag对象相当于一个字典,可以获取'href'None的值。

再复杂的学习可以参看三夜灯的blog文章(文后参考2)

Worked Example: BeautifulSoup

urllinks.py

  1. # To run this, you can install BeautifulSoup
  2. # https://pypi.python.org/pypi/beautifulsoup4
  3. # Or download the file
  4. # http://www.py4e.com/code3/bs4.zip
  5. # and unzip it in the same directory as this file
  6. import urllib.request, urllib.parse, urllib.error
  7. from bs4 import BeautifulSoup
  8. import ssl
  9. # Ignore SSL certificate errors
  10. ctx = ssl.create_default_context()
  11. ctx.check_hostname = False
  12. ctx.verify_mode = ssl.CERT_NONE
  13. url = input('Enter - ')
  14. html = urllib.request.urlopen(url, context=ctx).read()
  15. soup = BeautifulSoup(html, 'html.parser')
  16. # Retrieve all of the anchor tags
  17. tags = soup('a')
  18. for tag in tags:
  19. print(tag.get('href', None))

作业:Scraping HTML Data with BeautifulSoup

  1. # To run this, you can install BeautifulSoup
  2. # https://pypi.python.org/pypi/beautifulsoup4
  3. # Or download the file
  4. # http://www.py4e.com/code3/bs4.zip
  5. # and unzip it in the same directory as this file
  6. from urllib.request import urlopen
  7. from bs4 import BeautifulSoup
  8. import ssl
  9. # Ignore SSL certificate errors
  10. ctx = ssl.create_default_context()
  11. ctx.check_hostname = False
  12. ctx.verify_mode = ssl.CERT_NONE
  13. url = input('Enter - ')
  14. html = urlopen(url, context=ctx).read()
  15. soup = BeautifulSoup(html, "html.parser")
  16. # Retrieve all of the anchor tags
  17. tags = soup('span')
  18. count = 0
  19. sum = 0
  20. for tag in tags:
  21. # Look at the parts of a tag
  22. sum = sum + int(tag.contents[0])
  23. count += 1
  24. print ('Count ',count)
  25. print('Sum ', sum)

使用的是python3与bs4。

作业:Following Links in HTML Using BeautifulSoup

  1. # To run this, you can install BeautifulSoup
  2. # https://pypi.python.org/pypi/beautifulsoup4
  3. # Or download the file
  4. # http://www.py4e.com/code3/bs4.zip
  5. # and unzip it in the same directory as this file
  6. import urllib.request, urllib.parse, urllib.error
  7. from bs4 import BeautifulSoup
  8. import ssl
  9. import re
  10. # Ignore SSL certificate errors
  11. ctx = ssl.create_default_context()
  12. ctx.check_hostname = False
  13. ctx.verify_mode = ssl.CERT_NONE
  14. count = int(input("Enter count:"))
  15. position = int(input("Enter position:"))
  16. first_name = input("Start with:")
  17. def retrievinghtml(name):
  18. url = "http://py4e-data.dr-chuck.net/known_by_%s.html"%(name)
  19. html = urllib.request.urlopen(url, context=ctx).read()
  20. soup = BeautifulSoup(html, 'html.parser')
  21. # Retrieve all of the anchor tags
  22. tags = soup('a')
  23. temp_tag = tags[position-1]
  24. temp_site = temp_tag.get('href', None)
  25. temp_name = (re.findall('known_by_(\S+).html',temp_site))[0]
  26. print("Retrieving: "+"http://py4e-data.dr-chuck.net/known_by_%s.html"%(temp_name))
  27. return temp_name
  28. name = []
  29. name.append(first_name)
  30. print("Retrieving: "+"http://py4e-data.dr-chuck.net/known_by_%s.html"%(first_name))
  31. for i in range(count):
  32. temp_name = retrievinghtml(name[i])
  33. name.append(temp_name)
  34. print(name)

使用的仍然是python3与bs4。

【参考】

[1]龙的博客

[2]用python的BeautifulSoup分析html

《Using Python to Access Web Data》Week4 Programs that Surf the Web 课堂笔记的更多相关文章

  1. Python Web-第四周-Programs that Surf the Web(Using Python to Access Web Data)

    1.Understanding HTML 1.最简单的爬虫 import urllib fhand=urllib.urlopen('http://www.dr-chuck.com/page1.htm' ...

  2. Python Web-第二周-正则表达式(Using Python to Access Web Data)

    0.课程地址与说明 1.课程地址:https://www.coursera.org/learn/python-network-data/home/welcome 2.课程全名:Using Python ...

  3. 【Python学习笔记】Coursera课程《Using Python to Access Web Data》 密歇根大学 Charles Severance——Week6 JSON and the REST Architecture课堂笔记

    Coursera课程<Using Python to Access Web Data> 密歇根大学 Week6 JSON and the REST Architecture 13.5 Ja ...

  4. 【Python学习笔记】Coursera课程《Using Python to Access Web Data 》 密歇根大学 Charles Severance——Week2 Regular Expressions课堂笔记

    Coursera课程<Using Python to Access Web Data > 密歇根大学 Charles Severance Week2 Regular Expressions ...

  5. 《Using Python to Access Web Data》 Week5 Web Services and XML 课堂笔记

    Coursera课程<Using Python to Access Web Data> 密歇根大学 Week5 Web Services and XML 13.1 Data on the ...

  6. 《Using Python to Access Web Data》 Week3 Networks and Sockets 课堂笔记

    Coursera课程<Using Python to Access Web Data> 密歇根大学 Week3 Networks and Sockets 12.1 Networked Te ...

  7. paip. 解决php 以及 python 连接access无效的参数量。参数不足,期待是 1”的错误

    paip. 解决php 以及 python 连接access无效的参数量.参数不足,期待是 1"的错误 作者Attilax  艾龙,  EMAIL:1466519819@qq.com  来源 ...

  8. Python之路【第十八篇】:Web框架们

    Python之路[第十八篇]:Web框架们   Python的WEB框架 Bottle Bottle是一个快速.简洁.轻量级的基于WSIG的微型Web框架,此框架只由一个 .py 文件,除了Pytho ...

  9. Python之路【第十五篇】:Web框架

    Python之路[第十五篇]:Web框架   Web框架本质 众所周知,对于所有的Web应用,本质上其实就是一个socket服务端,用户的浏览器其实就是一个socket客户端. 1 2 3 4 5 6 ...

随机推荐

  1. centos7下通过LVS的DR模式实现负载均衡访问

    一.两台服务器作为real server ,一台作为director director:172.28.18.69 vip:172.28.18.70 real server1:172.28.18.71 ...

  2. (转) Linux权限管理(基本权限、默认权限)

    一.文件基本权限 1-1.基本权限的修改 -rw-r--r--  - 第一个"-"表示文件类型(- 文件,d 目录,l 软链接文件)  - rw-       r--       ...

  3. VMware主机使用无线上网

    VMware主机使用无线上网,默认的NAT连接在ubuntu下上不了网,需要把网络适配器改成桥接模式.

  4. json格式字符串转字典

    //json格式字符串转字典+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {        if (jsonStr ...

  5. Linux系统无法启动故障解决方案

    Linux系统无法启动故障解决方案 2011-09-27 09:42 佚名 比特网 我要评论(0) 字号:T | T 不管你多么喜爱你的Linux系统机器,有时候你都必须恢复你的系统.是的,即使一台L ...

  6. shiro框架学习-7- Shiro权限控制注解和编程方式

    讲解权限角色控制 @RequiresRoles, @RequiresPermissions等注解的使用和编程式控制 配置文件的方式 使用ShiroConfig 注解方式 @RequiresRoles( ...

  7. Redis实战(十三)Redis的三种集群方式

    序言 能聊聊redis cluster集群模式的原理吗 资料 https://www.cnblogs.com/51life/p/10233340.html Redis 集群分片原理

  8. UVa 11212 Editing a Book (IDA* && 状态空间搜索)

    题意:你有一篇n(2≤n≤9)个自然段组成的文章,希望将它们排列成1,2,…,n.可以用Ctrl+X(剪切)和Ctrl+V(粘贴)快捷键来完成任务.每次可以剪切一段连续的自然段,粘贴时按照顺序粘贴.注 ...

  9. 51 Nod 1678 lyk与gcd(容斥原理)

    1678 lyk与gcd  基准时间限制:2 秒 空间限制:131072 KB 分值: 80 难度:5级算法题  收藏  关注 这天,lyk又和gcd杠上了. 它拥有一个n个数的数列,它想实现两种操作 ...

  10. JS数据容量单位转换(kb,mb,gb,tb)

    JS代码如下: var size = '8164674'; function bytesToSize(bytes) { if (bytes === 0) return '0 B'; var k = 1 ...