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字典序问题实例
Sep 26 Python
python实现可将字符转换成大写的tcp服务器实例
Apr 29 Python
Python简单实现自动删除目录下空文件夹的方法
Aug 29 Python
使用Numpy读取CSV文件,并进行行列删除的操作方法
Jul 04 Python
Django objects的查询结果转化为json的三种方式的方法
Nov 07 Python
Pycharm之快速定位到某行快捷键的方法
Jan 20 Python
Python 实现两个服务器之间文件的上传方法
Feb 13 Python
深入了解Python iter() 方法的用法
Jul 11 Python
Django中ORM找出内容不为空的数据实例
May 20 Python
Python 字符串池化的前提
Jul 03 Python
python调用有道智云API实现文件批量翻译
Oct 10 Python
Windows安装Anaconda3的方法及使用过程详解
Jun 11 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 远程图片保存到本地的函数类
2008/12/08 PHP
PHP代码优化的53个细节
2014/03/03 PHP
php表单请求获得数据求和示例
2014/05/15 PHP
Thinkphp中的volist标签用法简介
2014/06/18 PHP
对PHP PDO的一些认识小结
2015/01/23 PHP
php实现将HTML页面转换成word并且保存的方法
2016/10/14 PHP
laravel 中如何使用ajax和vue总结
2017/08/16 PHP
通过JS获取用户本地图片路径并显示的代码
2012/02/16 Javascript
js获取指定日期前后的日期代码
2013/08/20 Javascript
javascript模拟post提交隐藏地址栏的参数
2014/09/03 Javascript
JS获取时间的方法
2015/01/21 Javascript
js的toUpperCase方法用法实例
2015/01/27 Javascript
Bootstrap CSS组件之导航(nav)
2016/12/17 Javascript
JavaScript面向对象编程小游戏---贪吃蛇代码实例
2019/05/15 Javascript
Element-ui中元素滚动时el-option超出元素区域的问题
2019/05/30 Javascript
nodejs和react实现即时通讯简易聊天室功能
2019/08/21 NodeJs
微信小程序抽奖组件的使用步骤
2021/01/11 Javascript
[52:09]2014 DOTA2华西杯精英邀请赛 5 25 NewBee VS DK第二场
2014/05/26 DOTA
Django Admin 实现外键过滤的方法
2017/09/29 Python
Python xlwt设置excel单元格字体及格式
2020/04/18 Python
numpy给array增加维度np.newaxis的实例
2018/11/01 Python
python的set处理二维数组转一维数组的方法示例
2019/05/31 Python
Python 获取 datax 执行结果保存到数据库的方法
2019/07/11 Python
python进阶之自定义可迭代的类
2019/08/20 Python
python中字典按键或键值排序的实现代码
2019/08/27 Python
python中树与树的表示知识点总结
2019/09/14 Python
浅析HTML5的WebSocket与服务器推送事件
2016/02/19 HTML / CSS
Foot Locker德国官方网站:美国运动服和鞋类零售商
2018/11/01 全球购物
办公室前台岗位职责
2014/01/04 职场文书
和平主题的演讲稿
2014/01/12 职场文书
2014年大学生村官工作总结
2014/11/19 职场文书
小学生禁毒教育心得体会
2016/01/15 职场文书
学校趣味运动会开幕词
2016/03/04 职场文书
《家世》读后感:看家训的力量
2019/12/30 职场文书
浅谈sql_@SelectProvider及使用注意说明
2021/08/04 Java/Android
MySQL一劳永逸永久支持输入中文的方法实例
2022/08/05 MySQL