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网络编程学习笔记(四):域名系统
Jun 09 Python
Python快速排序算法实例分析
Nov 29 Python
python数据封装json格式数据
Mar 04 Python
Python3删除排序数组中重复项的方法分析
Jan 31 Python
Python使用线程来接收串口数据的示例
Jul 02 Python
python2.7的flask框架之引用js&css等静态文件的实现方法
Aug 22 Python
python 导入数据及作图的实现
Dec 03 Python
Python图像处理库PIL的ImageGrab模块介绍详解
Feb 26 Python
django model通过字典更新数据实例
Apr 01 Python
如何安装并在pycharm使用selenium的方法
Apr 30 Python
如何打包Python Web项目实现免安装一键启动的方法
May 21 Python
自定义Django_rest_framework_jwt登陆错误返回的解决
Oct 18 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(4) php 函数 补充2
2010/02/15 PHP
jQuery 中关于CSS操作部分使用说明
2007/06/10 Javascript
浅说js变量
2011/05/25 Javascript
通过百度地图获取公交线路的站点坐标的js代码
2012/05/11 Javascript
javascript高级程序设计第二版第十二章事件要点总结(常用的跨浏览器检测方法)
2012/08/22 Javascript
JQuery 实现在同一页面锚点链接之间的平滑滚动
2014/10/29 Javascript
基于javascript的COOkie的操作实现只能点一次
2014/12/26 Javascript
node.js [superAgent] 请求使用示例
2015/03/13 Javascript
js中的内部属性与delete操作符介绍
2015/08/10 Javascript
js滑动提示效果代码分享
2016/03/10 Javascript
使用JQuery 加载页面时调用JS的实现方法
2016/05/30 Javascript
self.attachevent is not a function的解决方法
2017/04/04 Javascript
vue中配置mint-ui报css错误问题的解决方法
2017/10/11 Javascript
微信小程序实现图片上传、删除和预览功能的方法
2017/12/18 Javascript
微信小程序实现图片压缩功能
2018/01/26 Javascript
vue 之 css module的使用方法
2018/12/04 Javascript
如何写好一个vue组件,老夫的一年经验全在这了(推荐)
2019/05/18 Javascript
详解JWT token心得与使用实例
2019/08/02 Javascript
vue 集成jTopo 处理方法
2019/08/07 Javascript
详解JavaScript中的链式调用
2020/11/27 Javascript
python基础入门详解(文件输入/输出 内建类型 字典操作使用方法)
2013/12/08 Python
python如何实现远程控制电脑(结合微信)
2015/12/21 Python
浅谈Python中range和xrange的区别
2017/12/20 Python
python 阶乘累加和的实例
2019/02/01 Python
python生成特定分布数的实例
2019/12/05 Python
python 字典访问的三种方法小结
2019/12/05 Python
Python获取二维数组的行列数的2种方法
2020/02/11 Python
详解Pycharm与anaconda安装配置指南
2020/08/25 Python
如何利用python检测图片是否包含二维码
2020/10/15 Python
利用html5 file api读取本地文件示例(如图片、PDF等)
2018/03/07 HTML / CSS
Pop In A Box英国:Funko POP搪胶公仔
2019/05/27 全球购物
简述索引存取方法的作用和建立索引的原则
2013/03/26 面试题
写给女朋友的道歉信
2014/01/08 职场文书
《神奇的克隆》教学反思
2014/04/10 职场文书
道歉信范文
2015/05/12 职场文书
Pandas自定义选项option设置
2021/07/25 Python