python网络爬虫(第一章)
(内容来自于O’Reilly(人民邮电出版社)的《Python网络爬虫权威指南》此博客仅用于记录学习,方便以后使用)
目前本系列文章(python网络爬虫笔记)更新情况:
第一章:本文
第二章:python网络爬虫(第二章)
简单实例:python网络爬虫(简单实例)
欢迎大家查阅,有不足或错误之处不吝赐教
代码:
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup
def getTitle(url):
try:
html = urlopen(url)
except HTTPError as e:
return None
try:
bs = BeautifulSoup(html.read(), 'html.parser')
title = bs.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)
解释:
1、urllib是python的标准库,包含了从网页请求数据,处理cookie,甚至改变请求头和用户代理这些元数据的函数。urlopen用来打开并读取一个从网络获取的远程对象(可以轻松获取HTML文件、图像文件或其他任何文件流)
from url lib.request import url open
html = urlopen(‘http://pythonscraping.com/pages/page1.html')
print(html.read())
2、BeautifulSoup库:
可以将HTML内容传到BeautifulSoup对象
bs = BeautifulSoup(html.read(), ‘html.parser’)
#第一个参数是该对象所基于的HTML文本,第二个参数指定了你希望BeautifulSoup用来创建该对象的解析器。可供选择的解析器有’html.parser’、’lxml'、 #'html5lib'
3、异常处理
需要引入的标准库:
urllib.error
from urllib.error import HTTPError
#HTTP错误,网页在服务器上不存在(或者获取页面的时候出现错误)
from urllib.error import URLError
#服务器不存在
使用try + except的方式进行处理
调用None对象下面的字标签,会发生AttributeError错误
具体代码可以看本文最前面的综合代码