Python3 爬虫 1

来源:互联网 发布:b站直播间刷人气源码 编辑:程序博客网 时间:2024/06/07 00:56

爬虫的第一步需要将网页下载下来,下面介绍下载网页内容的方法。

download函数

import urllib.request ## Python2与Python3的区别def download(url):    req = urllib.request.Request(url)    response = urllib.request.urlopen(req)    return response.read()url = "http://example.webscraping.com/"html = download(url)print(html)

这样运行的结果是直接输出一大堆
download

我是直接使用Python3自带的IDLE写的程序,输出结果的时候经常卡死,所以可以选择将爬取下来的内容写入文件中,这样速度会快很多。

## 将结果写入到文件的改进版本,适用于英文网站import urllib.requestdef download(url):    req = urllib.request.Request(url)    response = urllib.request.urlopen(req)    return response.read().decode("utf-8")url = "http://example.webscraping.com/"html = download(url)html = str(html)## 将一大堆乱七八糟的代码转换为比较美观的格式html = html.replace("\xa0", " ")html = html.replace("\xa9", " ")html.encode("gbk")file_name = 'f:/Python/用Python写网络爬虫/练习/crawling_file.txt'file_open = open(file_name, "a")file_open.write(html)file_open.close()

这样执行之后会出现一个crawling_file.txt文件
文件


捕获异常

当下载网页时可能会出现一些无法控制的错误,下面给出一个更加健硕的版本。

import urllib.requestdef download(url):    try:        req = urllib.request.Request(url)        response = urllib.request.urlopen(req)        html = response.read().decode("utf-8")    except urllib.request.URLError as e:        print("Download error:", e.reason) ## 输出错误原因        html = None    return htmlurl = "http://httpstat.us/500"html = download(url)html = str(html)html = html.replace("\xa0", " ")html = html.replace("\xa9", " ")html.encode("gbk")file_name = 'f:/Python/用Python写网络爬虫/练习/crawling_try.txt'file_open = open(file_name, "w+")file_open.write(html)file_open.close()

程序中url执行的结果是
error
此时,可以尝试以下方式解决。

重试下载

不是所有的错误都适合重试下载,4 xx 错误发生在请求存在问题时,
而5xx 错误则发生在服务端存在问题时。所以, 我们只需要确保download函数在发生Sxx 错误时重试下载即可。

import urllib.requestdef download(url, num_retries = 2):    try:        req = urllib.request.Request(url)        response = urllib.request.urlopen(req)        html = response.read().decode("utf-8")    except urllib.request.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, num_retries-1) ## 递归调用    return htmlurl = "http://httpstat.us/500"html = download(url)html = str(html) ## 写入文件必须要求是str类型## 保证不是乱码切格式是美观的html = html.replace("\xa0", " ")html = html.replace("\xa9", " ")html.encode("gbk")## 文件的标准写法file_name = 'f:/Python/用Python写网络爬虫/练习/crawling_try_again.txt' ## 在这里只写入文件一次,因为重试下载是发生在有问题的时候,一旦恢复正常就不会再重试下载file_open = open(file_name, "a")file_open.write(html)file_open.close()