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 client使用http post 到server端的代码
Feb 10 Python
Python获取邮件地址的方法
Jul 10 Python
Python中在脚本中引用其他文件函数的实现方法
Jun 23 Python
用Python实现KNN分类算法
Dec 22 Python
解决Python下imread,imwrite不支持中文的问题
Dec 05 Python
Python面向对象程序设计中类的定义、实例化、封装及私有变量/方法详解
Feb 28 Python
python 经典数字滤波实例
Dec 16 Python
flask框架自定义url转换器操作详解
Jan 25 Python
解决TensorFlow GPU版出现OOM错误的问题
Feb 03 Python
pandas实现excel中的数据透视表和Vlookup函数功能代码
Feb 14 Python
django使用JWT保存用户登录信息
Apr 22 Python
Python包资源下载路径报404解决方案
Nov 05 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版(3)
2006/10/09 PHP
destoon会员注册提示“数据校验失败(2)”解决方法
2014/06/21 PHP
php利用cookie实现自动登录的方法
2014/12/10 PHP
PHP5.5新特性之yield理解与用法实例分析
2019/01/11 PHP
JS将制定内容复制到剪切板示例代码
2014/02/11 Javascript
JQuery中serialize()、serializeArray()和param()方法示例介绍
2014/07/31 Javascript
jQuery实现的简单百分比进度条效果示例
2016/08/01 Javascript
AngularJS ng-mousedown 指令
2016/08/02 Javascript
详解Jquery Easyui的验证扩展
2017/01/09 Javascript
使用live-server快速搭建本地服务器+自动刷新的方法
2018/03/09 Javascript
vue2.0 根据状态值进行样式的改变展示方法
2018/03/13 Javascript
axios使用拦截器统一处理所有的http请求的方法
2018/11/02 Javascript
通过JS运行机制的角度说说作用域
2019/03/12 Javascript
详解JavaScript中关于this指向的4种情况
2019/04/18 Javascript
解决vue单页面应用中动态修改title问题
2019/06/09 Javascript
javascript实现的字符串转换成数组操作示例
2019/06/13 Javascript
vue实现鼠标经过动画
2019/10/16 Javascript
Python open读写文件实现脚本
2008/09/06 Python
python的dict,set,list,tuple应用详解
2014/07/24 Python
小米5s微信跳一跳小程序python源码
2018/01/08 Python
python将秒数转化为时间格式的实例
2018/09/16 Python
Python异常处理知识点总结
2019/02/18 Python
Django处理Ajax发送的Get请求代码详解
2019/07/29 Python
python解释器pycharm安装及环境变量配置教程图文详解
2020/02/26 Python
jupyter notebook 恢复误删单元格或者历史代码的实现
2020/04/17 Python
Tahari ASL官方网站:高级设计师女装
2021/03/15 全球购物
物理教育专业毕业生推荐信
2013/11/03 职场文书
男方父母证婚词
2014/01/12 职场文书
自荐信需注意事项
2014/01/25 职场文书
清扬洗发水广告词
2014/03/14 职场文书
学校花圃的标语
2014/06/18 职场文书
中国梦读书活动总结
2014/07/10 职场文书
邹越感恩父母演讲稿
2014/08/28 职场文书
公安机关查摆剖析材料
2014/10/10 职场文书
2014年保洁工作总结
2014/11/24 职场文书
2016年国陪研修感言
2015/11/18 职场文书