爬虫学习,第一节课 Your First Web Scraper

来源:互联网 发布:筹码分布软件 编辑:程序博客网 时间:2024/05/20 03:40

说明

学习笔记,用的例子都是书上或者改了几个字符的0 0

版本和依赖包


Python 3.52
标准包 urllib
依赖包 BeautifulSoup
包管理工具 pip(全地球人都在使用的)

urllib.request中urlopen的使用

urllib是python标准包里面的一个,在python3中被分成了三大模块,无需安装就可以马上使用,当然需要import,而这里只用到其中一个urlopen.request的function。

from urllib.request import urlopenhtml = urlopen("www.baidu.com")print(html.read())

使用这段代码就可以在console里面打印出百度首页这个宇宙最强搜索器的首页html内容,好像不止html,才刚入门就先不探究了。

BeautifulSoup

可以看到上面得到的html内容异常混乱,蛇鼠一锅,而python最好的地方在于肯定一个一个包能用在小地方,所以,书上介绍可以用BeautifulSoup来美化。
BeautifulSoup不是一个标准包,需要下载安装,肯定得懒懒的用pip。

值得注意的是
1.使用pip需要安装 “beautifulsoup4”,后面是有”4”的
2.import的时候需要引入的是”BS4”

使用BeautifulSoup写法如下:

from urllib.request import urlopenfrom bs4 import BeautifulSouphtml = urlopen("http://www.baidu.com")bsObj = BeautifulSoup(html.read())print(bsObj.html)

使用console里面也是一团糟 - -///,但是总算是有了分行。壮我宇宙第一搜索器的强大的前端。

使用bs4生成的bsObj是:

>>> type(bsObj)<class 'bs4.BeautifulSoup'>

这个对象可以通过是类似于javascript的链式调用

bsObj.html.body.h1bsObj.body.h1bsObj.html.h1

捕获错误

为了防止各种出错造成的爬虫爬着爬着就趴了的情况,得启用try-exceptionde的组合
通过HTTPError捕获请求错误,通过AttributeError捕获空请求错误等。
书上的例子如下。

from urllib.request import urlopenfrom urllib.error import HTTPErrorfrom bs4 import BeautifulSoupdef getTitle(url):    try:        html_responce = urlopen(url)        html_bytes = html_responce.read()        html = html_bytes.decode("gbk")    except HTTPError as e:        return None    try:        bsObj = BeautifulSoup(html, "html.parser")        title = bsObj.body.h1    except AttributeError as e:        return None    return titletitle = getTitle("http://www.qq.com")if title == None:    print("Ttile could not be found")else:    print(title)

问题

原版的代码出现了编码错误
通过增加在读取html的responce 后增加解码html = html_bytes.decode("gbk")错误得到了解决,显示出中文

pydev debugger: process 13340 is connectingConnected to pydev debugger (build 162.1967.10)<h1><a class="qqlogo" href="http://www.qq.com" target="_blank"><span class="undis">腾讯网</span></a></h1>Process finished with exit code 0

编码问题得到了解决

0 0