python网络爬虫(第一章)

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错误
具体代码可以看本文最前面的综合代码

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值