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的socket模块源码中的一些实现要点分析
Jun 06 Python
python装饰器-限制函数调用次数的方法(10s调用一次)
Apr 21 Python
Python骚操作之动态定义函数
Mar 26 Python
利用python如何在前程无忧高效投递简历
May 07 Python
Python 3 判断2个字典相同
Aug 06 Python
PIL对上传到Django的图片进行处理并保存的实例
Aug 07 Python
Tensorflow 实现释放内存
Feb 03 Python
TensorFlow实现从txt文件读取数据
Feb 05 Python
python shapely.geometry.polygon任意两个四边形的IOU计算实例
Apr 12 Python
python继承threading.Thread实现有返回值的子类实例
May 02 Python
python利用 keyboard 库记录键盘事件
Oct 16 Python
pytorch 运行一段时间后出现GPU OOM的问题
Jun 02 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新手上路(九)
2006/10/09 PHP
一个PHP的String类代码
2010/04/20 PHP
PHP对MongoDB[NoSQL]数据库的操作
2013/03/01 PHP
PHP可变函数的使用详解
2013/06/14 PHP
php实现无限级分类(递归方法)
2015/08/06 PHP
PHP yii实现model添加默认值的方法(两种方法)
2016/11/10 PHP
用Javascript 获取页面元素的位置的代码
2009/09/25 Javascript
jquery 弹出登录窗口实现代码
2009/12/24 Javascript
Javascript面向对象设计一 工厂模式
2011/12/20 Javascript
js解析xml字符串和xml文档实现原理及代码(针对ie与火狐)
2013/02/02 Javascript
javascript中的五种基本数据类型
2015/08/26 Javascript
javaScript事件机制兼容【详细整理】
2016/07/23 Javascript
Bootstrap源码学习笔记之bootstrap进度条
2016/12/24 Javascript
angular使用post、get向后台传参的问题实例
2017/05/27 Javascript
js装饰设计模式学习心得
2018/02/17 Javascript
Vue实现用户自定义字段显示数据的方法
2018/08/28 Javascript
JS/CSS实现字符串单词首字母大写功能
2019/09/03 Javascript
vue点击Dashboard不同内容 跳转到同一表格的实例
2020/11/13 Javascript
Python有序字典简单实现方法示例
2017/09/28 Python
python re模块findall()函数实例解析
2018/01/19 Python
python数据预处理 :数据共线性处理详解
2020/02/24 Python
python标准库OS模块详解
2020/03/10 Python
Matplotlib中rcParams使用方法
2021/01/05 Python
解决Python import .pyd 可能遇到路径的问题
2021/03/04 Python
CSS3弹性盒模型开发笔记(一)
2016/04/26 HTML / CSS
深入了解canvas在移动端绘制模糊的问题解决
2019/04/30 HTML / CSS
Subside Sports德国:足球球衣和球迷商品
2019/06/08 全球购物
C#里面如何倒序排列一个数组的元素?
2013/06/21 面试题
书法大赛策划方案
2014/06/04 职场文书
团日活动总结怎么写
2014/06/25 职场文书
国际金融专业自荐信
2014/07/05 职场文书
领导干部“四风”问题批评与自我批评材料
2014/09/24 职场文书
美容院员工规章制度
2015/08/05 职场文书
经销商会议开幕词
2016/03/04 职场文书
导游词之白茶谷九龙峡
2019/10/23 职场文书
Python中itertools库的四个函数介绍
2022/04/06 Python