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]' : '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.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. java 程序编写规则(自己总结)

    1.命名规范 (1)所有的标示符都只能用ASCⅡ字母(A-Z或a-z).数字(0-9)和下划线"_". (2)类名是一个名词,采用大小写混合的方式,每个单词的首字母大写.例如:Us ...

  2. python之进程----Queue

    一.Queue是通过multiprocessing使用 from multiprocessing import Process,Queue import time import random impo ...

  3. Java NIO vs IO

    NIO :http://tutorials.jenkov.com/java-nio/index.html IO:http://tutorials.jenkov.com/java-io/index.ht ...

  4. mysql水平分表和垂直分表的优缺点

    表分割有两种方式: 1.水平分割:根据一列或多列数据的值把数据行放到两个独立的表中. 水平分割通常在下面的情况下使用. •表很大,分割后可以降低在查询时需要读的数据和索引的页数,同时也降低了索引的层数 ...

  5. 关于maven项目的一些报错问题

    本文为自己记录的笔记略显粗糙后续会把遇到的问题追加进来.忘大神多指点 1.父工程红色感叹号 此类问题解决方法,一般打开pom文件查看红色标记处是否有报错,也就是看哪个jar包没有下下来.分为两种情况. ...

  6. Failed to load the JNI shared library "XXXXXXX"

    今天启动Eclipse的时候出现了这个问题,经过查找, 一般来说这种问题都是因为eclipse 和Java 的兼容性不一致所导致的. 1) 查看Eclipse 和Java 版本 那么我们需要分别查看下 ...

  7. 翻译 | 使用A-Frame打造WebVR版《我的世界》

    原文地址:Minecraft in WebVR with HTML Using A-Frame 原文作者:Kevin Ngo 译者:Felix 校对:阿希 我是 Kevin Ngo,一名就职于 Moz ...

  8. java文档操作

    背景:因是动态报表,1)作成excel模版2)数据填充3)转化为PDF提出解决方法:[open source]1)Apache Poi+I text2) JodConvert+OpenOffice/l ...

  9. Linux学习——shell编程之环境变量配置文件

    小白学习,在学习中总结! shell编程之环境变量配置文件 一:环境变量配置文件 1 shell编程之环境变量配置 变量类型: 用户自定义变量(本地变量) 环境变量 :定义每个用户的操作环境,如pat ...

  10. poj2337欧拉回路要求输出路径

                         Catenyms Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 8368   Ac ...