python简单爬虫代码-Python爬虫――写出最简单的网页爬虫

最近对python爬虫有了强烈地兴趣,在此分享自己的学习路径,欢迎大家提出建议。我们相互交流,共同进步。

1.开发工具

笔者使用的工具是sublime text3,它的短小精悍(可能男人们都不喜欢这个词)使我十分着迷。推荐大家使用,当然如果你的电脑配置不错,pycharm可能更加适合你。

sublime text3搭建python开发环境推荐查看此博客:

[sublime搭建python开发环境][http://www.cnblogs.com/codefish/p/4806849.html]

2.爬虫介绍

爬虫顾名思义,就是像虫子一样,爬在Internet这张大网上。如此,我们便可以获取自己想要的东西。

既然要爬在Internet上,那么我们就需要了解URL,法号"统一资源定位器”,小名"链接”。其结构主要由三部分组成:

(1)协议:如我们在网址中常见的HTTP协议。

(2)域名或者IP地址:域名,如:www.baidu.com,IP地址,即将域名解析后对应的IP。

(3)路径:即目录或者文件等。

3.urllib开发最简单的爬虫

(1)urllib简介

Module

Introduce

urllib.error

Exception classes raised by urllib.request.

urllib.parse

Parse URLs into or assemble them from components.

urllib.request

Extensible library for opening URLs.

urllib.response

Response classes used by urllib.

urllib.robotparser

Load a robots.txt file and answer questions about fetchability of other URLs.

(2)开发最简单的爬虫

百度首页简洁大方,很适合我们爬虫。

爬虫代码如下:

fromurllib import request

def visit_baidu():

URL = "http://www.baidu.com"

# openthe URL

req = request.urlopen(URL)

# readthe URL

html = req.read()

# decode the URL toutf-8

html = html.decode("utf_8")

print(html)

if __name__ == '__main__':

visit_baidu()

结果如下图:

wKiom1mKtwyxE1yxAAGxMm_vDic947.png-wh_651x-s_2133535518.png

我们可以通过在百度首页空白处右击,查看审查元素来和我们的运行结果对比。

当然,request也可以生成一个request对象,这个对象可以用urlopen方法打开。

代码如下:

fromurllib import request

def vists_baidu():

# createa request obkect

req = request.Request('http://www.baidu.com')

# openthe request object

response = request.urlopen(req)

# readthe response

html = response.read()

html = html.decode('utf-8')

print(html)

if __name__ == '__main__':

vists_baidu()

运行结果和刚才相同。

(3)错误处理

错误处理通过urllib模块来处理,主要有URLError和HTTPError错误,其中HTTPError错误是URLError错误的子类,即HTTRPError也可以通过URLError捕获。

HTTPError可以通过其code属性来捕获。

处理HTTPError的代码如下:

fromurllib import request

fromurllib import error

def Err():

url = "https://segmentfault.com/zzz"

req = request.Request(url)

try:

response = request.urlopen(req)

html = response.read().decode("utf-8")

print(html)

excepterror.HTTPErrorase:

print(e.code)

if __name__ == '__main__':

Err()

运行结果如图:

wKiom1mKt2TCZpUlAAAFDkrzwBI901.png

404为打印出的错误代码,关于此详细信息大家可以自行百度。

URLError可以通过其reason属性来捕获。

chuliHTTPError的代码如下:

fromurllib import request

fromurllib import error

def Err():

url = "https://segmentf.com/"

req = request.Request(url)

try:

response = request.urlopen(req)

html = response.read().decode("utf-8")

print(html)

excepterror.URLErrorase:

print(e.reason)

if __name__ == '__main__':

Err()

运行结果如图:

wKiom1mKuELQouS_AAAH0hssSPE054.png

既然为了处理错误,那么***两个错误都写入代码中,毕竟越细致越清晰。须注意的是,HTTPError是URLError的子类,所以一定要将HTTPError放在URLError的前面,否则都会输出URLError的,如将404输出为Not Found。

代码如下:

fromurllib import request

fromurllib import error

# ***种方法,URLErroe和HTTPError

def Err():

url = "https://segmentfault.com/zzz"

req = request.Request(url)

try:

response = request.urlopen(req)

html = response.read().decode("utf-8")

print(html)

excepterror.HTTPErrorase:

print(e.code)

excepterror.URLErrorase:

print(e.reason)

大家可以更改url来查看各种错误的输出形式。

【编辑推荐】

【责任编辑:枯木 TEL:(010)68476606】

点赞 0