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 相关文章推荐
详解Django缓存处理中Vary头部的使用
Jul 24 Python
Python基于回溯法子集树模板解决数字组合问题实例
Sep 02 Python
教你用Python写安卓游戏外挂
Jan 11 Python
VScode编写第一个Python程序HelloWorld步骤
Apr 06 Python
Python cookbook(数据结构与算法)将多个映射合并为单个映射的方法
Apr 19 Python
Python简单实现网页内容抓取功能示例
Jun 07 Python
Python读写zip压缩文件的方法
Aug 29 Python
Python之虚拟环境virtualenv,pipreqs生成项目依赖第三方包的方法
Jul 23 Python
python+mysql实现个人论文管理系统
Oct 25 Python
Python openpyxl 插入折线图实例
Apr 17 Python
Java Unsafe类实现原理及测试代码
Sep 15 Python
详解Python中__new__方法的作用
Mar 31 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&java(一)
2006/10/09 PHP
smarty的保留变量问题
2008/10/23 PHP
Thinkphp框架开发移动端接口(2)
2016/08/18 PHP
PHP中的使用curl发送请求(GET请求和POST请求)
2017/02/08 PHP
javaScript面向对象继承方法经典实现
2013/08/20 Javascript
对table和ul实现js分页示例分享
2014/02/24 Javascript
javascript读写json示例
2014/04/11 Javascript
js实现简单计算器
2015/11/22 Javascript
jQuery获取访问者IP地址的方法(基于新浪API与QQ查询接口)
2016/05/25 Javascript
jQuery如何获取动态添加的元素
2016/06/24 Javascript
AngularJS中transclude用法详解
2016/11/03 Javascript
JS实现搜索框文字可删除功能
2016/12/28 Javascript
JavaScript数据结构之二叉树的计数算法示例
2017/04/13 Javascript
通过fastclick源码分析彻底解决tap“点透”
2017/12/24 Javascript
JavaScript比较同一天的时间大小实例代码
2018/02/09 Javascript
浅谈Webpack下多环境配置的思路
2018/06/27 Javascript
浅谈Angularjs中不同类型的双向数据绑定
2018/07/16 Javascript
微信小程序实现的canvas合成图片功能示例
2019/05/03 Javascript
VUE 直接通过JS 修改html对象的值导致没有更新到数据中解决方法分析
2019/12/02 Javascript
OpenCV实现人脸识别
2017/04/07 Python
Python三种遍历文件目录的方法实例代码
2018/01/19 Python
Python tkinter事件高级用法实例
2018/01/31 Python
Python3自动签到 定时任务 判断节假日的实例
2018/11/13 Python
python3.6根据m3u8下载mp4视频
2019/06/17 Python
python使用tomorrow实现多线程的例子
2019/07/20 Python
python3.6 tkinter实现屏保小程序
2019/07/30 Python
python 利用turtle模块画出没有角的方格
2019/11/23 Python
python3 使用traceback定位异常实例
2020/03/09 Python
python中count函数知识点浅析
2020/12/17 Python
python字典与json转换的方法总结
2020/12/28 Python
css3截图_动力节点Java学院整理
2017/07/11 HTML / CSS
HTML5 在canvas中绘制矩形附效果图
2014/06/23 HTML / CSS
HTML5去掉输入框type为number时的上下箭头的实现方法
2020/01/03 HTML / CSS
英国第一的购买便宜玩具和游戏的在线购物网站:Bargain Max
2018/01/24 全球购物
严选全球尖货,立足香港:Bonpont宝盆
2018/07/24 全球购物
《纸船和风筝》教学反思
2016/02/18 职场文书