python 网络爬虫(二)

一、编写第一个网络爬虫

  为了抓取网站,我们需要下载含有感兴趣的网页,该过程一般被称为爬取(crawling)。爬取一个网站有多种方法,而选择哪种方法更加合适,则取决于目标网站的结构。

  首先探讨如何安全的下载网页,让后介绍3中爬去网站的常见方法:

    -- 爬取网站地图;

    -- 遍历每个网页的数据库 ID;

    -- 跟踪网页链接;

1、下载网页

  要想爬取网页,我们首先将其下载下来。下面的实例脚本使用 Python 的 urllib2 模块下载 URL:

import urllib2
def download(url):
    return urllib2.urlopen(url).read()

  当传入 URL 参数时,该函数将会下载网页并返回其 HTML 。不过,这个代码片段存在一个问题,即当下载网页时,饿哦们可能会遇到一些无法控制的错误,比如请求的页面可能不存在,此时,urllib2 会抛出异常,然后退出脚本。安全起见,下面给出一个更健壮的版本,可以捕获这些异常:

import urllib2

def download(url):
    print('Downloading:', url)
    try:
        html = urllib2.urlopen(url).read()
    except urllib2.URLError as e:
        print('Download error:', e.reason)
        html = None
        
    return html

现在,当出现下载错误是,该函数能够捕获异常,然后返回 None。

当 download 函数遇到 5xx 错误码时,将会递归调用函数自身进行重试。

import urllib2

def download(url, num_retries = 2):
    print('Downloading:', url)
    try:
        html = urllib2.urlopen(url).read()
    except urllib2.URLError as e:
        print('Download error:', e.reason)
        html = None
        if num_retries > 0:
            if hasattr(e, 'code') and 500 <= e.code < 00:
                return download(url, num_retries - 1)

此外,该函数还增加了一个参数,用于设定重试下载的次数,其默认值为两次。

 

2、设置用户代理

  默认情况下,urllib2 使用 Python-urllib/2.7 作为用户下载网页内容,其中 2.7 是 python的版本号,如果能使用可辨别的用户代理则更好。这样可以避免爬虫遇到的一些问题。此外,也许是因为曾经经历过质量不佳的Python网络爬虫造成的服务器过载,一些网站还会封禁这个默认的用户代理。

  因此,为了下载更可考,我们需要控制用户代理的设定。下面代码对 download 函数进行了修改。设定了一个默认的用户代理 “wswp”(即 We Scraping with Python 的手字母缩写)

import urllib2

def download(url, user_agent = 'wswp', num_retries = 2):
    print('Downloading :', url)
    headers = {'User-agent':user_agent}
    request = urllib2.Request(url, headers = headers)
    try:
        html = urllib2.urlopen(request).read()
    except urllib2.URLError as e:
        print('Download error:', e.reason)
        html = None
        
        if num_retries > 0:
            if hasattr(e, 'code') and 500 <= e.code < 600:
                return download(url, user_agent, num_retries - 1)
      
    return html

现在我们拥有一个灵活的下载函数,该函数能够捕获异常,重试下载并设置了用户代理。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

 

posted on 2019-05-15 17:34  海纳百川_有容乃大  阅读(156)  评论(0编辑  收藏  举报

导航