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]' : '12345@qq.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]' : '12334@qq.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)

python3 抓取网页资源的 N 种方法的更多相关文章

  1. python3爬取网页

    爬虫 python3爬取网页资源方式(1.最简单: import'http://www.baidu.com/'print2.通过request import'http://www.baidu.com' ...

  2. php抓取网页中的内容

    以下就是几种常用的用php抓取网页中的内容的方法.1.file_get_contentsPHP代码代码如下:>>>>>>>>>>>&g ...

  3. php抓取网页

    用php抓取页面的内容在实际的开发其中是很实用的,如作一个简单的内容採集器,提取网页中的部分内容等等.抓取到的内容在通过正則表達式做一下过滤就得到了你想要的内容.下面就是几种经常使用的用php抓取网页 ...

  4. Python3简单爬虫抓取网页图片

    现在网上有很多python2写的爬虫抓取网页图片的实例,但不适用新手(新手都使用python3环境,不兼容python2), 所以我用Python3的语法写了一个简单抓取网页图片的实例,希望能够帮助到 ...

  5. Python3抓取javascript生成的html网页

    用urllib等抓取网页,只能读取网页的静态源文件,而抓不到由javascript生成的内容. 究其原因,是因为urllib是瞬时抓取,它不会等javascript的加载延迟,所以页面中由javasc ...

  6. python3下scrapy爬虫(第四卷:初步抓取网页内容之抓取网页里的指定数据延展方法)

    上卷中我运用创建HtmlXPathSelector 对象进行抓取数据: 现在咱们再试一下其他的方法,先试一下我得最爱XPATH 看下结果: 直接打印出结果了 我现在就正常拼下路径 只求打印结果: 现在 ...

  7. [Python]网络爬虫(一):抓取网页的含义和URL基本构成

    一.网络爬虫的定义 网络爬虫,即Web Spider,是一个很形象的名字. 把互联网比喻成一个蜘蛛网,那么Spider就是在网上爬来爬去的蜘蛛.网络蜘蛛是通过网页的链接地址来寻找网页的. 从网站某一个 ...

  8. python抓取网页引用的模块和类

    在Python3.x中,我们可以使用urlib这个组件抓取网页,urllib是一个URL处理包,这个包中集合了一些处理URL的模块,如下:1.urllib.request模块用来打开和读取URLs:2 ...

  9. PHP的CURL方法curl_setopt()函数案例介绍(抓取网页,POST数据)

    通过curl_setopt()函数可以方便快捷的抓取网页(采集很方便),curl_setopt 是php的一个扩展库 使用条件:需要在php.ini 中配置开启.(PHP 4 >= 4.0.2) ...

随机推荐

  1. Hadoop-HBASE案例分析-Hadoop学习笔记<二>

    之前有幸在MOOC学院抽中小象学院hadoop体验课. 这是小象学院hadoop2.X概述第八章的笔记 主要介绍HBase,一个分布式数据库的应用案例. 案例概况: 1)时间序列数据库(OpenTSD ...

  2. Linux Socket编程

    “一切皆Socket!” 话虽些许夸张,但是事实也是,现在的网络编程几乎都是用的socket. ——有感于实际编程和开源项目研究. 我们深谙信息交流的价值,那网络中进程之间如何通信,如我们每天打开浏览 ...

  3. (转载)robots.txt写法大全和robots.txt语法的作用

    1如果允许所有搜索引擎访问网站的所有部分的话 我们可以建立一个空白的文本文档,命名为robots.txt放在网站的根目录下即可.robots.txt写法如下:User-agent: *Disallow ...

  4. Asp.Net Core--基于角色的授权

    翻译如下: 当创建身份时,它可以属于一个或多个角色,例如Tracy可以属于管理员和用户角色,而Scott可以仅属于用户角色. 如何创建和管理这些角色取决于授权过程的后备存储. 角色通过ClaimsPr ...

  5. java基础 集合类

    java集合类主要有以下集中: List结构的集合类: ArrayList类, LinkedList类, Vector类, Stack类 Map结构的集合类: HashMap类,Hashtable类 ...

  6. oracle中 SELECT INTO 和INSERT INTO ... SELECT区别

    在Oracle中,将一张表的数据复制到另外一个对象中.通常会有这两种方法:insert into select  和 select into from. 前者可以将select 出来的N行(0到任意数 ...

  7. linux升级openssh

    升级sshd到OpenSSH-6.7并删除老版本ssh 1)升级前准备 查看是否缺包 # rpm -qa | egrep "gcc|make|perl|pam|pam-devel" ...

  8. jquery 控件赋值

    input 文本框赋值$("#id").attr("赋值"); input 文本框清空$("#id").attr("") ...

  9. HTTP TCP UDP Socket 关系的几个经典图

      从上图可以看到,TCP/IP是个协议组,可分为三个层次:网络层.传输层和应用层. 在网络层有IP协议.ICMP协议.ARP协议.RARP协议和BOOTP协议. 在传输层中有TCP协议与UDP协议. ...

  10. ASP.NET MVC中的错误处理

    ASP.NET MVC中的错误的错误处理跨越了两个主要领域:程序异常和路由异常的处理.前者是关于在控制器和视图中捕获错误的;而后者更多是有关重定向和HTTP错误的. 1.在WebConfig中把过滤器 ...