urllib是python的一个获取url(Uniform Resource Locators,统一资源定址器)了,我们可以利用它来抓取远程的数据进行保存哦,下面整理了一些关于urllib使用中的一些关于header,代理,超时,认证,异常处理处理方法,下面一起来看看。

python3 抓取网页资源的 N 种方法

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]' : ''
}
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]' : ''
}
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.111cn.net ')
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://www.111cn.net /")
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://www.111cn.net /")
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://www.111cn.net /"
password_mgr.add_password(None, top_level_url, 'rekfan', 'xxxxxx')
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://www.111cn.net /"
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://www.111cn.net ").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://www.111cn.net /')
a = urllib.request.urlopen(req).read()
print(a)

Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)的更多相关文章

  1. Python3中urllib详细使用方法(header,代理,超时,认证,异常处理) 转

    urllib是python的一个获取url(Uniform Resource Locators,统一资源定址器)了,我们可以利用它来抓取远程的数据进行保存哦,下面整理了一些关于urllib使用中的一些 ...

  2. 【转】Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)

      urllib是python的一个获取url(Uniform Resource Locators,统一资源定址器)了,我们可以利用它来抓取远程的数据进行保存哦,下面整理了一些关于urllib使用中的 ...

  3. Python3中使用urllib的方法详解(header,代理,超时,认证,异常处理)_python

    我们可以利用urllib来抓取远程的数据进行保存哦,以下是python3 抓取网页资源的多种方法,有需要的可以参考借鉴. 1.最简单 import urllib.request response = ...

  4. Python3中使用urllib的方法详解(header,代理,超时,认证,异常处理)

    出自  http://www.jb51.net/article/93125.htm

  5. Python2和Python3中urllib库中urlencode的使用注意事项

    前言 在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urlencode的包 ...

  6. python3中使用builtwith的方法(很详细)

    1. 首先通过pip install builtwith安装builtwith C:\Users\Administrator>pip install builtwith Collecting b ...

  7. python3中urllib库的request模块详解

    刚刚接触爬虫,基础的东西得时时回顾才行,这么全面的帖子无论如何也得厚着脸皮转过来啊! 原帖地址:https://www.2cto.com/kf/201801/714859.html 什么是 Urlli ...

  8. Python3中Urllib库基本使用

    什么是Urllib? Python内置的HTTP请求库 urllib.request          请求模块 urllib.error              异常处理模块 urllib.par ...

  9. 常见的爬虫分析库(1)-Python3中Urllib库基本使用

    原文来自:https://www.cnblogs.com/0bug/p/8893677.html 什么是Urllib? Python内置的HTTP请求库 urllib.request          ...

随机推荐

  1. Jenkins邮件配置,实现邮件发送策略(可实现每个Job对应不同的发送邮箱)

    前言: 首先,要有一个用来发送的邮箱,首选网易!参考:http://www.cnblogs.com/EasonJim/p/6051636.html,这里我注册了网易的免费企业邮箱. 并且我新建没多个邮 ...

  2. WHMCS系统API调用

    WHMCS:域名管理系统,现在网络上很多借助此系统Shadowsocks插件+ShadowsocksR多用户服务端进行VPN的售卖,能做到流量控制等. 在对接此系统的API时,我发现了很多功能都已经实 ...

  3. Jenkins实现生产环境部署文件的回滚操作(Windows)

    由于dotnet项目的生产环境环境部署工具比较少,所以我使用jenkins作为生产环境的自动化部署工具. 既然有回滚操作,那么就会有部署操作:要实现回滚,先要实现部署的操作,我在jenkins搭建了一 ...

  4. 保存密码(KeyChain的使用)

    1.导入框架Security.framework 2.编写工具类 /* 该工具类只能保存一个用户和密码 */ /* service 一般为 bundle ID */ @interface GLKeyC ...

  5. 需要获取设备方向变化(UIDeviceOrientation)的消息

    如果需要获得UIDeviceOrientation的转换消息的话,只需要: [[UIDevice currentDevice] beginGeneratingDeviceOrientationNoti ...

  6. struts2文件目录结构

    apps 文件夹包含了多个 example 示例应用的压缩包. docs 文件夹包含了 struts 官方的帮助文档. lib 文件夹包含了 struts 提供的类库 jar 包. src 文件夹包含 ...

  7. 淘淘商城maven工程的创建和svn的上传实现

    后台管理系统工程结构 maven管理的好处 1.项目构建.Maven定义了软件开发的整套流程体系,并进行了封装,开发人员只需要指定项目的构建流程,无需针对每个流程编写自己的构建脚本. 2.依赖管理.除 ...

  8. 【原】javascript最佳实践

    摘要:这篇文章主要内容的来源是<javascript高级程序设计第三版>,因为第二遍读完,按照书里面的规范,发觉自己在工作中没有好好遵守.所以此文也是对自己书写js的一种矫正. 1.可维护 ...

  9. css的核心内容 标准流、盒子模型、浮动、定位等分析

    1.块级元素:如:<div></div>2.行内元素:如:<span></span>从效果中看块级元素与行内元素的区别: 通过CSS的设置把行内元素转换 ...

  10. c++异常捕获

    概念: “C++异常”就是 try{}catch(...){} “SEH异常”就是 __try{} __except(-//){} (关于这两种异常,如有不了解的地方,网上有很多资料可以参考) 目前微 ...