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中使用psutil查看内存占用的情况
Jun 11 Python
TensorFlow实现Logistic回归
Sep 07 Python
Django中ORM外键和表的关系详解
May 20 Python
使用OpenCV实现仿射变换—旋转功能
Aug 29 Python
Python安装及Pycharm安装使用教程图解
Sep 20 Python
python实现按首字母分类查找功能
Oct 31 Python
使用 Python ssh 远程登陆服务器的最佳方案
Mar 06 Python
完美解决pyinstaller打包报错找不到依赖pypiwin32或pywin32-ctypes的错误
Apr 01 Python
Python函数的迭代器与生成器的示例代码
Jun 18 Python
python输出结果刷新及进度条的实现操作
Jul 13 Python
Python循环之while无限迭代
Apr 30 Python
python神经网络学习 使用Keras进行回归运算
May 04 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数组传递是值传递而非引用传递概念纠正
2013/01/31 PHP
[原创]php获取数组中键值最大数组项的索引值
2015/03/17 PHP
php+ajax登录跳转登录实现思路
2016/07/31 PHP
分享14个很酷的jQuery导航菜单插件
2011/04/25 Javascript
Javascript操作cookie的函数代码
2012/10/03 Javascript
javascript loadScript异步加载脚本示例讲解
2013/11/14 Javascript
使用javascript控制cookie显示和隐藏背景图
2014/02/12 Javascript
鼠标拖拽移动子窗体的JS实现
2014/02/25 Javascript
javascript跨域的4种方法和原理详解
2014/04/08 Javascript
JavaScript通过setTimeout实时显示当前时间的方法
2015/04/16 Javascript
easyui validatebox验证
2016/04/29 Javascript
js简单正则验证汉字英文及下划线的方法
2016/11/28 Javascript
jQuery实现复选框的全选和反选
2017/02/02 Javascript
通过学习bootstrop导航条学会修改bootstrop颜色基调
2017/06/11 Javascript
javascript连接mysql与php通过odbc连接任意数据库的实例
2017/12/27 Javascript
详解Webpack多环境代码打包的方法
2018/08/03 Javascript
JSONP原理及应用实例详解
2018/09/13 Javascript
Vue源码探究之虚拟节点的实现
2019/04/17 Javascript
uploadify插件实现多个图片上传并预览
2019/09/30 Javascript
Python入门篇之条件、循环
2014/10/17 Python
python爬虫之urllib库常用方法用法总结大全
2018/11/14 Python
pytorch GAN伪造手写体mnist数据集方式
2020/01/10 Python
python isinstance函数用法详解
2020/02/13 Python
Django QuerySet查询集原理及代码实例
2020/06/13 Python
python如何快速生成时间戳
2020/07/21 Python
使用phonegap操作数据库的实现方法
2017/03/31 HTML / CSS
墨尔本最受欢迎的复古风格品牌:Princess Highway
2018/12/21 全球购物
高性能钓鱼服装:Huk Gear
2019/02/20 全球购物
预备党员综合考察材料
2014/05/31 职场文书
数学教师个人总结
2015/02/06 职场文书
求职信内容一般写什么?
2015/03/20 职场文书
幼儿园毕业致辞
2015/07/29 职场文书
推广普通话宣传标语口号
2015/12/26 职场文书
导游词之上海东方明珠塔
2019/09/25 职场文书
pytorch 使用半精度模型部署的操作
2021/05/24 Python
「魔导具师妲莉亚永不妥协~从今天开始的自由职人生活~」1、2卷发售宣传CM公开
2022/03/21 日漫