Web Scraping with Python第一章

1. 认识urllib

urllib是python的标准库,它提供丰富的函数例如从web服务器请求数据、处理cookie等,在python2中对应urllib2库,不同于urllib2,python3的urllib被分为若干子模块:urllib.request、urllib.parse、urllib.error等,urllib库的使用可以参考https://docs.python.org/3/library/urllib.html

from urllib.request import urlopen
html = urlopen("http://pythonscraping.com/pages/page1.html")
print(html.read())
b‘<html>\n<head>\n<title>A Useful Page</title>\n</head>\n<body>\n<h1>An Interesting Title</h1>\n<div>\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n</div>\n</body>\n</html>\n‘

2. 认识BeautifulSoup

BeautifulSoup库用于解析html文本,并转化为BeautifulSoup对象。

from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
bsObj = BeautifulSoup(html.read(),"lxml")
print(bsObj.h1)
<h1>An Interesting Title</h1>

BeautifulSoup函数需要制定解析库,下表列出常见的几种解析库,并给出优缺点:

解析库 使用方法 优势 劣势
Python标准库 BeautifulSoup(html,’html.parser’) Python内置标准库;执行速度快 容错能力较差
lxml HTML解析库 BeautifulSoup(html,’lxml’) 速度快;容错能力强 需要安装,需要C语言库
lxml XML解析库 BeautifulSoup(html,[‘lxml’,’xml’]) 速度快;容错能力强;支持XML格式 需要C语言库
htm5lib解析库 BeautifulSoup(html,’htm5llib’) 以浏览器方式解析,最好的容错性 速度慢

3. 可靠性爬虫

我们知道在网站访问中通常会出现404 Page not found的情况,或者服务器暂时关闭了,在调用urlopen函数时就会抛出异常,使得程序无法继续运行,我们可以urllib.error模块来处理异常。

from urllib.request import urlopen
from urllib.error import URLError

try:
    html = urlopen("https://www.baid.com/")   #url is wrong
except URLError as e:
    print(e)
<urlopen error [Errno 111] Connection refused>

在取得可靠性连接后,我们用BeautifulSoup处理html,通常会出现网站改版后无法找到某个标签从而抛出异常的情形。

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page1.html")
try:
    bsObj = BeautifulSoup(html.read(),"lxml")
    li = bsObj.ul.li
    print(li)
except AttributeError as e:
    print(e)
‘NoneType‘ object has no attribute ‘li‘

4. 第一个爬虫程序

from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup

def getTitle(url):
    try:
        html = urlopen(url)
    except HTTPError as e:
        return None

    try:
        bsObj = BeautifulSoup(html.read(),"lxml")
        title = bsObj.body.h1
    except AttributeError as e:
        return None

    return title

title = getTitle("http://www.pythonscraping.com/pages/page1.html")
if title == None:
    print("Title could not be found.")
else:
    print(title)
<h1>An Interesting Title</h1>

原文地址:https://www.cnblogs.com/dxs959229640/p/8660834.html

时间: 2024-08-29 12:30:32

Web Scraping with Python第一章的相关文章

简学Python第一章__进入PY的世界

#cnblogs_post_body h2 { background: linear-gradient(to bottom, #18c0ff 0%,#0c7eff 100%); color: #fff; height: 55px width:100% -moz-border-radius: 3px; padding: 3px; margin: 10px 0px; font-family: "微软雅黑", "宋体", "黑体", Arial } P

headfirst python第一章初始python速记卡

headfirst python这本书非常不错,但是很多人没耐心读,出的速记卡,有用的尽管下载headfirst python第一章初识python速记卡.rar原书下载HeadfirstPython.pdf 原文地址:https://blog.51cto.com/382392/2386391

python第一章小结

第一章总结 一.简述编译型与解释型语言的区别,且分别列出你知道的哪些语言属于编译型,哪些属于解释型 编译器是把源程序的每一条语句都编译成机器语言,并保存成二进制文件,这样运行时计算机可以直接以机器语言来运行此程序,速度很快; 如C C++ Delphi 等语言是编译型语言 而解释器则是只在执行程序时,才一条一条的解释成机器语言给计算机来执行,所以运行速度是不如编译后的程序运行的快的. ----跨平台. 如Python Java PHP Ruby等语言是解释型语言 高级语言所编制的程序不能被计算机

Web Scraping using Python Scrapy_BS4 - Introduction

What is Web Scraping This is also referred to as web harvesting and web data extraction. This is the process of automatically downloading a web page's data and extracting information from it. Benefits of Web Scraping Component of applications used fo

python第一章练习题

本章总节 练习题 1.简述编译型与解释型语言的区别,且分别列出你知道的哪些语言属于编译型,哪些属于解释 编译型:把源代码编译成机器语言的可执行文件,程序执行的时候执行可执行文件即可. 优点:程序执行不需要源代码,不依赖语言环境,执行速度快,因为执行的是机器码文件,计算机可以直接读懂 缺点:每次修改源代码都需要重新编译.跨平台性不好,不同的操作系统,调用底层的机器指令不同,需为不同平台生产不同的机器码文件 编译型语言:如C.C++,Delphi 解释型: 用户调用解释器,执行源代码文件,解释器把源

初识Python第一章

一:开发语言: 高级语言:Python,Java,  C#  PHP  Go   ruby  C++  ===>> 字节码 低级语言: C, 汇编                       ===>> 机器码 语言之间的对比:PHP做页面网站且快速搭建环境 ,有局限性:Java python不仅写页面,还可以写后台功能. -Python 执行效率低,开发效率高. -Java  执行效率高,开发效率低. python种类: JPython   IronPython  Cpython

python第一章

在终端直接输入Python,进入Python,Python -v 查看版本,quit();exit();ctrl+d,退出Python 注意:Python对缩进要求很严格,因为它的程序代码是没有结尾符号的,是通过缩进去判断的.官方推荐空格4个 Python变量: 1.标识符的第一个字符必须是字母表中的字母(大写或小写),或者一个下划线('--') 2,标识符名称的其他部分可以由字母.下划线或数字组成. 3,标识符名称是对大小写敏感的,例:myname 和mYname不是一个标识符,大小不同. 4

Python 第一章 【基础篇】

Python 简介    Python 安装    第一个Python程序         Python 解释器         字符编码与解码      动态语言与静态语言的区别   变量及简单数据类型 编码规范 Python前世今生 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC语言的一种继承. 最新的TIOBE排行榜,Python赶超PHP占据第五!!! 由上

python 第一章 介绍-1.python特点.

一.Python特点 开源免费 脚本语言,解析执行 跨平台 高级语言,面向对象,可扩展,可移植性用于在不同的平台(因为Python是用C写的,又由于C的可移植性) 内存管理器在Python中,由于内存管理是由Python解释器负责的,所以开发人员就可以从内存事物中解放出来,全神关注于直接目标.解释性语言,不需要编译,连接成可执行的exe文件代码 Google后台就是用Python写的,现在国内大型软件公司的后台基本 它的特点如下: ------------------------- 1.高级编程