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 dict remove数组删除(del,pop)
Mar 24 Python
Python中解析JSON并同时进行自定义编码处理实例
Feb 08 Python
Python模拟鼠标点击实现方法(将通过实例自动化模拟在360浏览器中自动搜索python)
Aug 23 Python
轻量级的Web框架Flask 中模块化应用的实现
Sep 11 Python
numpy.random.seed()的使用实例解析
Feb 03 Python
Python使用matplotlib实现基础绘图功能示例
Jul 03 Python
Python 实现Windows开机运行某软件的方法
Oct 14 Python
Python3实现取图片中特定的像素替换指定的颜色示例
Jan 24 Python
python自动化测试无法启动谷歌浏览器问题
Oct 10 Python
django rest framework使用django-filter用法
Jul 15 Python
忆童年!用Python实现愤怒的小鸟游戏
Jun 07 Python
pandas中pd.groupby()的用法详解
Jun 16 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引用(&)各种使用方法实例详解
2014/03/20 PHP
javaScript 数值型和字符串型之间的转换
2009/07/25 Javascript
不同浏览器的怪癖小结
2010/07/11 Javascript
JS拖动技术 关于setCapture使用
2010/12/09 Javascript
Javascript 闭包引起的IE内存泄露分析
2012/05/23 Javascript
JS多物体 任意值 链式 缓冲运动
2012/08/10 Javascript
原生js写的放大镜效果
2012/08/22 Javascript
JS跨域总结
2012/08/30 Javascript
jQuery的slideToggle方法实例
2013/05/07 Javascript
JavaScript四种调用模式和this示例介绍
2014/01/02 Javascript
jQuery 获取/设置/删除DOM元素的属性以a元素为例
2014/05/23 Javascript
BootStrap入门教程(二)之固定的内置样式
2016/09/19 Javascript
React Native之ListView实现九宫格效果的示例
2017/08/02 Javascript
微信小程序 循环及嵌套循环的使用总结
2017/09/26 Javascript
深入Vue-Router路由嵌套理解
2018/08/13 Javascript
JS canvas绘制五子棋的棋盘
2020/05/28 Javascript
python实现批量获取指定文件夹下的所有文件的厂商信息
2014/09/28 Python
Python中.py文件打包成exe可执行文件详解
2017/03/22 Python
numpy.linspace函数具体使用详解
2019/05/27 Python
利用python实现汉字转拼音的2种方法
2019/08/12 Python
Python 迭代,for...in遍历,迭代原理与应用示例
2019/10/12 Python
Pycharm最常用的快捷键及使用技巧
2020/03/05 Python
五款漂亮的纯CSS3动画按钮的实例教程
2014/11/21 HTML / CSS
CSS3弹性盒模型开发笔记(二)
2016/04/26 HTML / CSS
html5中如何将图片的绝对路径转换成文件对象
2018/01/11 HTML / CSS
使用html2canvas实现将html内容写入到canvas中生成图片
2020/01/03 HTML / CSS
马来西亚最好的婴儿商店:Motherhood
2017/09/14 全球购物
印度在线购买电子产品网站:Croma
2020/01/02 全球购物
高中毕业的自我鉴定
2013/12/09 职场文书
优秀的导游求职信范文
2014/04/06 职场文书
外联部演讲稿
2014/05/24 职场文书
工作期间打牌检讨书范文
2014/11/20 职场文书
警告通知
2015/04/25 职场文书
学习焦裕禄观后感
2015/06/09 职场文书
保险公司岗前培训工作总结
2015/10/24 职场文书
instantclient客户端 连接oracle数据库
2022/04/26 Oracle