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 fileinput模块使用介绍
Nov 30 Python
python编程测试电脑开启最大线程数实例代码
Feb 09 Python
python实现本地图片转存并重命名的示例代码
Oct 27 Python
解决python写入带有中文的字符到文件错误的问题
Jan 31 Python
Appium+python自动化怎么查看程序所占端口号和IP
Jun 14 Python
用Python实现校园通知更新提醒功能
Nov 23 Python
查看端口并杀进程python脚本代码
Dec 17 Python
python实现逆滤波与维纳滤波示例
Feb 26 Python
Python中操作各种多媒体,视频、音频到图片的代码详解
Jun 04 Python
python中return如何写
Jun 18 Python
从python读取sql的实例方法
Jul 21 Python
忆童年!用Python实现愤怒的小鸟游戏
Jun 07 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
main.php
2006/12/09 PHP
发一个php简单的伪原创程序,配合商城采集用的
2010/10/12 PHP
PHP的变量总结 新手推荐
2011/04/18 PHP
PHP中将ip地址转成十进制数的两种实用方法
2013/08/15 PHP
php中cookie的使用方法
2014/03/29 PHP
PHP  实现等比压缩图片尺寸和大小实例代码
2016/10/08 PHP
解决用jquery load加载页面到div时,不执行页面js的问题
2014/02/22 Javascript
javascript中的遍历for in 以及with的用法
2014/12/22 Javascript
js实现数组冒泡排序、快速排序原理
2016/03/08 Javascript
基于javascript实现九宫格大转盘效果
2020/05/28 Javascript
Vue.js计算属性computed与watch(5)
2016/12/09 Javascript
JavaScript的数据类型转换原则(干货)
2018/03/15 Javascript
[原创]jquery判断元素内容是否为空的方法
2018/05/04 jQuery
vue上传图片到oss的方法示例(图片带有删除功能)
2018/09/27 Javascript
vue里input根据value改变背景色的实例
2018/09/29 Javascript
总结4个方面优化Vue项目
2019/02/11 Javascript
微信小程序学习笔记之目录结构、基本配置图文详解
2019/03/28 Javascript
vue添加锚点,实现滚动页面时锚点添加相应的class操作
2020/08/10 Javascript
UEditor 自定义图片视频尺寸校验功能的实现代码
2020/10/20 Javascript
Vue SPA 首屏优化方案
2021/02/26 Vue.js
Python2.x与Python3.x的区别
2016/01/14 Python
http请求 request失败自动重新尝试代码示例
2018/01/25 Python
Numpy掩码式数组详解
2018/04/17 Python
python散点图实例之随机漫步
2018/08/27 Python
VSCode Python开发环境配置的详细步骤
2019/02/22 Python
python pip源配置,pip配置文件存放位置的方法
2019/07/12 Python
使用python模拟命令行终端的示例
2019/08/13 Python
Python新手学习标准库模块命名
2020/05/29 Python
python 爬取免费简历模板网站的示例
2020/09/27 Python
html5用video标签流式加载的实现
2020/05/20 HTML / CSS
线程问题:wait()方法是定义在哪个类里面
2015/07/07 面试题
主管会计岗位职责
2014/03/13 职场文书
竞赛口号大全
2014/06/16 职场文书
大学教师师德师风演讲稿
2014/08/22 职场文书
创先争优个人承诺书
2014/08/30 职场文书
民主生活会对照检查材料思想汇报
2014/09/27 职场文书