python3实现抓取网页资源的 N 种方法


Posted in Python onMay 02, 2017

这两天学习了python3实现抓取网页资源的方法,发现了很多种方法,所以,今天添加一点小笔记。

1、最简单

import urllib.request
response = urllib.request.urlopen('http://python.org/')
html = response.read()

2、使用 Request

import urllib.request
 
req = urllib.request.Request('http://python.org/')
response = urllib.request.urlopen(req)
the_page = response.read()

3、发送数据

#! /usr/bin/env python3
 
import urllib.parse
import urllib.request
 
url = 'http://localhost/login.php'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {
     'act' : 'login',
     'login[email]' : 'yzhang@i9i8.com',
     'login[password]' : '123456'
     }
 
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data)
req.add_header('Referer', 'http://www.python.org/')
response = urllib.request.urlopen(req)
the_page = response.read()
 
print(the_page.decode("utf8"))

4、发送数据和header

#! /usr/bin/env python3
 
import urllib.parse
import urllib.request
 
url = 'http://localhost/login.php'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {
     'act' : 'login',
     'login[email]' : 'yzhang@i9i8.com',
     'login[password]' : '123456'
     }
headers = { 'User-Agent' : user_agent }
 
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
the_page = response.read()
 
print(the_page.decode("utf8"))

5、http 错误

#! /usr/bin/env python3
 
import urllib.request
 
req = urllib.request.Request('http://www.python.org/fish.html')
try:
  urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
  print(e.code)
  print(e.read().decode("utf8"))

6、异常处理1

#! /usr/bin/env python3
 
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request("http://twitter.com/")
try:
  response = urlopen(req)
except HTTPError as e:
  print('The server couldn\'t fulfill the request.')
  print('Error code: ', e.code)
except URLError as e:
  print('We failed to reach a server.')
  print('Reason: ', e.reason)
else:
  print("good!")
  print(response.read().decode("utf8"))

7、异常处理2

#! /usr/bin/env python3
 
from urllib.request import Request, urlopen
from urllib.error import URLError
req = Request("http://twitter.com/")
try:
  response = urlopen(req)
except URLError as e:
  if hasattr(e, 'reason'):
    print('We failed to reach a server.')
    print('Reason: ', e.reason)
  elif hasattr(e, 'code'):
    print('The server couldn\'t fulfill the request.')
    print('Error code: ', e.code)
else:
  print("good!")
  print(response.read().decode("utf8"))

8、HTTP 认证

#! /usr/bin/env python3
 
import urllib.request
 
# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
 
# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "https://cms.tetx.com/"
password_mgr.add_password(None, top_level_url, 'yzhang', 'cccddd')
 
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
 
# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)
 
# use the opener to fetch a URL
a_url = "https://cms.tetx.com/"
x = opener.open(a_url)
print(x.read())
 
# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)
 
a = urllib.request.urlopen(a_url).read().decode('utf8')
print(a)

9、使用代理

#! /usr/bin/env python3
 
import urllib.request
 
proxy_support = urllib.request.ProxyHandler({'sock5': 'localhost:1080'})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)

 
a = urllib.request.urlopen("http://g.cn").read().decode("utf8")
print(a)

10、超时

#! /usr/bin/env python3
 
import socket
import urllib.request
 
# timeout in seconds
timeout = 2
socket.setdefaulttimeout(timeout)
 
# this call to urllib.request.urlopen now uses the default timeout
# we have set in the socket module
req = urllib.request.Request('http://twitter.com/')
a = urllib.request.urlopen(req).read()
print(a)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
在Python中使用__slots__方法的详细教程
Apr 28 Python
python实现带声音的摩斯码翻译实现方法
May 20 Python
Linux 发邮件磁盘空间监控(python)
Apr 23 Python
使用Python编写一个最基础的代码解释器的要点解析
Jul 12 Python
Python实现返回数组中第i小元素的方法示例
Dec 04 Python
Python 十六进制整数与ASCii编码字符串相互转换方法
Jul 09 Python
python实现dijkstra最短路由算法
Jan 17 Python
java中的控制结构(if,循环)详解
Jun 26 Python
使用 PyTorch 实现 MLP 并在 MNIST 数据集上验证方式
Jan 08 Python
Python识别处理照片中的条形码
Nov 16 Python
python3中布局背景颜色代码分析
Dec 01 Python
Python爬虫:从m3u8文件里提取小视频的正确操作
May 14 Python
Pycharm学习教程(2) 代码风格
May 02 #Python
Pycharm学习教程(1) 定制外观
May 02 #Python
pycharm安装图文教程
May 02 #Python
python安装教程 Pycharm安装详细教程
May 02 #Python
python处理xml文件的方法小结
May 02 #Python
python实现的AES双向对称加密解密与用法分析
May 02 #Python
python中安装模块包版本冲突问题的解决
May 02 #Python
You might like
PHP 删除文件与文件夹操作 unlink()与rmdir()这两个函数的使用
2011/07/17 PHP
php Imagick获取图片RGB颜色值
2014/07/28 PHP
PHP中生成UUID自定义函数分享
2015/06/10 PHP
PHP基于堆栈实现的高级计算器功能示例
2017/09/15 PHP
jQuery使用手册之三 CSS操作
2007/03/24 Javascript
jQuery入门知识简介
2010/03/04 Javascript
简单漂亮的js弹窗可自由拖拽且兼容大部分浏览器
2013/10/22 Javascript
浅谈js数据类型判断与数组判断
2016/08/29 Javascript
利用Angular.js限制textarea输入的字数
2016/10/20 Javascript
Angularjs中使用layDate日期控件示例
2017/01/11 Javascript
jquery实现全选、全不选以及单选功能
2017/03/23 jQuery
微信小程序首页的分类功能和搜索功能的实现思路及代码详解
2018/09/11 Javascript
如何在Node和浏览器控制台中打印彩色文字
2020/01/09 Javascript
Vue如何实现变量表达式选择器
2021/02/18 Vue.js
[03:16]DOTA2完美大师赛小组赛精彩集锦
2017/11/22 DOTA
[01:47]2018年度DOTA2最佳教练-完美盛典
2018/12/16 DOTA
[45:44]完美世界DOTA2联赛PWL S2 FTD vs PXG 第一场 11.27
2020/12/01 DOTA
python获取当前目录路径和上级路径的实例
2018/04/26 Python
python 模拟贷款卡号生成规则过程解析
2019/08/30 Python
Django框架model模型对象验证实现方法分析
2019/10/02 Python
利用pyshp包给shapefile文件添加字段的实例
2019/12/06 Python
python使用梯度下降和牛顿法寻找Rosenbrock函数最小值实例
2020/04/02 Python
基于python实现上传文件到OSS代码实例
2020/05/09 Python
tensorflow pb to tflite 精度下降详解
2020/05/25 Python
Python叠加矩形框图层2种方法及效果
2020/06/18 Python
关于 HTML5 的七个传说小结
2012/04/12 HTML / CSS
中专生自荐信
2013/10/12 职场文书
珍珠鸟教学反思
2014/02/01 职场文书
酒店副总经理岗位职责范本
2014/02/04 职场文书
《我的信念》教学反思
2014/02/15 职场文书
拉歌口号大全
2014/06/13 职场文书
人事经理岗位职责范本
2014/08/04 职场文书
歌颂党的演讲稿
2014/09/10 职场文书
学生抄袭作业的检讨书
2014/10/02 职场文书
vue2实现provide inject传递响应式
2021/05/21 Vue.js
springboot中rabbitmq实现消息可靠性机制详解
2021/09/25 Java/Android