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)
这样运行的结果是直接输出一大堆
我是直接使用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执行的结果是
此时,可以尝试以下方式解决。
重试下载
不是所有的错误都适合重试下载,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()
阅读全文
0 0
- Python3 爬虫 1
- Python爬虫(1),Python3.x
- Python3:网络爬虫(1)
- python3 爬虫
- python3爬虫
- python3 爬虫
- Python3 爬虫
- python3 爬虫学习——1
- Python3.5.2网络爬虫教程(1)
- Python3爬虫学习1:入门篇
- python3爬虫1--简单网页源代码获取
- python3 多线程爬虫
- 自制 Python3爬虫
- python3.4-小爬虫
- python3基本爬虫
- Python3.4爬虫编程
- Python3.x爬虫
- Python3写简单爬虫
- hadoop(三):hdfs 机架感知
- Kubernetes之kubectl常用命令使用指南:1:创建和删除
- Android更新UI的四种方法详解
- jQuery检测判断复选框是否被选中了的几种方法
- 手机k歌高分必备神器——BBS掌中宝Q1
- Python3 爬虫 1
- Android ROM移植相关/内核学习
- C++静态库与动态库详解与使用
- redis数据库
- Struts2文件上传
- maven项目的建立中出错
- mysql 中 时间和日期函数
- JavaScript:理解事件、事件处理函数、钩子函数、回调函数
- Java网络编程