注:文章原文为Dr. Charles Severance 的 《Python for Informatics》。文中代码用3.4版改写,并在本机测试通过。

12.9 词汇表

BeautifulSoup: 一个用于分析HTML文档,并从中抓取数据的Python库。它弥补了大部分在浏览器中被忽略的HTML缺陷。你可以从www.crummy.com下载BeautifulSoup代码。

port:端口。当你用套接字链接服务器,通常表示正在联系的的服务器应用程序的数字。例如,网页服务使用80端口,电子邮件服务使用25端口。

scrape:一个程序伪装成一个网页浏览器,获取一个页面,然后查看网页的内容。经常程序会跟随一个页面中链路去找到下个页面,这样它们可以穿越一个网页网络或社交网络。

tōngchángbiǎoshìnínzhèngzàiliándeyìngyòngchéngdeshù

when you make a socket connection to a server. As an example, web traffic

socket:套接字。两个应用程序之间的网络连接。这样程序可以双向发送和接收数据。

spider:网络爬虫。网页搜索引擎通过获取一个页面和此页面的所有链接,循环搜索至几乎拥有互联网所有页面,并据此建立搜索索引的一种行为。

12.10 练习

 以下练习代码均为译者编写,仅供参考

练习 12.1 修改socket1.py,提示用户输入URL,使程序可以读取任何网页。你可以用split('/')方法分解URL的组成部门,使你可以抽取套接字连接调用的主机名。使用try和except语句添加错误校验,处理用户输入不正确格式的或不存在的URL。

  1. import socket
  2. import re
  3.  
  4. url = input('Enter an URL like this: http://www.py4inf.com/code/socket1.py\n')
  5. if (re.search('^http://[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+/',url)):
  6. words = url.split('/')
  7. hostname = words[2]
  8. mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  9. try:
  10. mysocket.connect((hostname, 80)) # 注意是两个圆括号
  11. except:
  12. print(hostname, ' is not a correct web server')
  13. exit
  14. mysocket.send(str.encode('GET ' + url + ' HTTP/1.0\n\n'))
  15. while True:
  16. data = mysocket.recv(1024).decode('utf-8')
  17. if (len(data) < 1):
  18. break
  19. print (data)
  20. mysocket.close()
  21. else:
  22. print("The URL that you input is bad format")

练习12.2 修改你的socket程序,使它具备对接收的字符进行计数的功能,并在显示3000个字符后停机显示。程序应该获取整个文档,对所有字符进行计数,并在文档最后显示字符数。

  1. import socket
  2. import re
  3.  
  4. url = input('Enter an URL like this: http://www.py4inf.com/code/socket1.py\n')
  5. if (re.search('^http://[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+/',url)):
  6. words = url.split('/')
  7. hostname = words[2]
  8. mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  9. try:
  10. mysocket.connect((hostname, 80)) # 注意是两个圆括号
  11. except:
  12. print(hostname, ' is not a correct server')
  13. exit
  14. mysocket.send(str.encode('GET ' + url + ' HTTP/1.0\n\n'))
  15. count = 0
  16. while True:
  17. data = mysocket.recv(3000).decode('utf-8')
  18. if (len(data) < 1):
  19. break
  20. count = count + len(data)
  21. if (count <= 3000):
  22. print (data)
  23. print("The total count of this web is", count)
  24. mysocket.close()
  25.  
  26. else:
  27. print("The URL that you input is bad format")

练习12.3 使用urllib库复制先前练习中的功能。(1)通过URL获取文档。(2)最多显示3000个字符。(3)对整个文档进行计数。不要担心这个练习的文件头,只需简单显示文档内容的前3000个字符。

  1. import urllib.request
  2. import re
  3.  
  4. url = input('Enter an URL like this: http://www.py4inf.com/code/socket1.py\n')
  5.  
  6. if (re.search('^http://[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+/',url)):
  7. try:
  8. web = urllib.request.urlopen(url)
  9. except:
  10. print(url, ' is not a valid url')
  11. exit
  12.  
  13. counts = 0
  14. while True:
  15. data = web.read(3000)
  16. if (len(data) < 1):
  17. break
  18. counts = counts + len(data)
  19. if (counts <= 3000):
  20. print (data.decode('utf-8'))
  21. print("The total counts of this web is", counts)
  22.  
  23. else:
  24. print("The URL that you input is bad format")

练习12.4 修改urllinks.py程序,使它抽取和统计所获取的HTML文档中的段标签(p),并显示段标签的数量。不需显示段的内容,只是统计即可。分别在几个小网页和一些长网页上测试你的程序。

  1. from bs4 import BeautifulSoup
  2. import urllib.request
  3.  
  4. url = input('Enter - ')
  5. html = urllib.request.urlopen(url).read()
  6. soup = BeautifulSoup(html,"html.parser")
  7. tags = soup('p')
  8. counts = 0
  9. for tag in tags:
  10. counts = counts + 1
  11. print('This web has ',counts, ' tags of p.')

练习12.5(高级)修改socket程序,使它只显示文件头和空行之后的数据。切记recv只接收字符(换行符及所有),而不是行。

  1. import socket
  2. import re
  3.  
  4. url = input('Enter an URL like this: http://www.py4inf.com/code/socket1.py\n')
  5. if (re.search('^http://[a-zA-Z0-9]+\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+/',url)):
  6. words = url.split('/')
  7. hostname = words[2]
  8.  
  9. mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  10. try:
  11. mysocket.connect((hostname, 80)) # 注意是两个圆括号
  12. except:
  13. print(hostname, ' is not a correct server')
  14. exit
  15.  
  16. mysocket.send(str.encode('GET ' + url + ' HTTP/1.0\n\n'))
  17. web = b''
  18. while True:
  19. data = mysocket.recv(1024)
  20. if (len(data) < 1):
  21. break
  22. web = web + data
  23. mysocket.close()
  24.  
  25. pos = web.find(b'\r\n\r\n')
  26. print(web[pos+4:].decode('utf-8'))
  27. else:
  28. print("The URL that you input is bad format")

Python for Infomatics 第12章 网络编程六(译)的更多相关文章

  1. Python for Infomatics 第12章 网络编程一(译)

    注:文章原文为Dr. Charles Severance 的 <Python for Informatics>.文中代码用3.4版改写,并在本机测试通过. 本书中的许多例子关注的是读取文件 ...

  2. Python for Infomatics 第12章 网络编程五(译)

    注:文章原文为Dr. Charles Severance 的 <Python for Informatics>.文中代码用3.4版改写,并在本机测试通过. 12.8 用urllib读取二进 ...

  3. Python for Infomatics 第12章 网络编程四(译)

    注:文章原文为Dr. Charles Severance 的 <Python for Informatics>.文中代码用3.4版改写,并在本机测试通过. 12.7 用BeautifulS ...

  4. Python for Infomatics 第12章 网络编程三(译)

    注:文章原文为Dr. Charles Severance 的 <Python for Informatics>.文中代码用3.4版改写,并在本机测试通过. 12.5 HTML分析和网页抓取 ...

  5. Python for Infomatics 第12章 网络编程二(译)

    注:文章原文为Dr. Charles Severance 的 <Python for Informatics>.文中代码用3.4版改写,并在本机测试通过. 12.3 用HTTP协议获取一张 ...

  6. python之路(12)网络编程

    前言 基于网络通信(AF_INET)的socket(套接字)实现了TCP/UDP协议 目录 基于TCP协议的socket 基于UDP协议的socket TCP协议下粘包现象及处理 使用socketse ...

  7. CSAPP:第十一章 网络编程

    CSAPP:第十一章 网络编程 11.1 客户端服务器模型11.2 全球IP因特网11.3 套接字接口 11.1 客户端服务器模型   每个网络应用都是基于客户端-服务器模型.采用这个模型,一个应用是 ...

  8. Python学习day34-面向对象和网络编程总结

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  9. 《深入浅出Node.js》第7章 网络编程

    @by Ruth92(转载请注明出处) 第7章 网络编程 Node 只需要几行代码即可构建服务器,无需额外的容器. Node 提供了以下4个模块(适用于服务器端和客户端): net -> TCP ...

随机推荐

  1. QT中将ASCII转换为对应数值的方法

    有时候需要将一段ASCII转换为数值进行传输(比如串口) QString str=codeEdit->toPlainText(); QVector<uint>v=str.toUcs4 ...

  2. [Nhibernate]SchemaExport工具的使用(一)——通过映射文件修改数据表

    目录 写在前面 文档与系列文章 SchemaExport工具 SchemaUpdate工具 一个例子 总结 写在前面 上篇文章介绍了使用代码生成器的nhibernate模版来生成持久化类,映射文件等内 ...

  3. thinkphp一句话疑难解决笔记 2

    php中的_ _call()方法? 它是php5后为对象 类 新增的一个自动方法. 它会监视类的其他方法的调用, 当调用类的不存在的方法时, 会自动调用类的__call方法. tp的 "命名 ...

  4. C# 发送电子邮件

    网上找到的发送邮件的类,改了一点点,在此谢谢原作者的奉献. 1.源码: public class CSendMail { private MailMessage mailMessage; privat ...

  5. CSS透明代码

    透明往往能产生不错的网页视觉效果,先奉上兼容主流浏览器的CSS透明代码: .transparent_class { filter:alpha(opacity=50); -moz-opacity:0.5 ...

  6. PHP curl获取页面内容,不直接输出到页面,CURLOPT_RETURNTRANSFER参数设置

    使用PHP curl获取页面内容或提交数据,有时候希望返回的内容作为变量储存,而不是直接输出.这个时候就必需设置curl的或true. 1.curl获取页面内容, 直接输出例子: <?php $ ...

  7. c#微信开发 转

    using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System. ...

  8. (转载)robots.txt写法大全和robots.txt语法的作用

    1如果允许所有搜索引擎访问网站的所有部分的话 我们可以建立一个空白的文本文档,命名为robots.txt放在网站的根目录下即可.robots.txt写法如下:User-agent: *Disallow ...

  9. javascript数据结构-栈

    github博客地址 栈(stack)又名堆栈,它是一种运算受限的线性表.遵循后进先出原则,像垃圾桶似的.功能实现依然按照增删改查来进行,内部数据存储可以借用语言原生支持的数组. 栈类 functio ...

  10. 垂直居中display:table;

    父级元素 display:table: 子元素 display:table-cell:vertical-align:middle: