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

 更新时间:2017年05月02日 14:21:54   作者:方倍工作室  
这两天学习了python3实现抓取网页资源的方法,发现了很多种方法,所以,今天添加一点小笔记。

这两天学习了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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • PyCharm Anaconda配置PyQt5开发环境及创建项目的教程详解

    PyCharm Anaconda配置PyQt5开发环境及创建项目的教程详解

    这篇文章主要介绍了PyCharm Anaconda配置PyQt5开发环境及创建项目的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-03-03
  • Python 通过监听端口实现唯一脚本运行方式

    Python 通过监听端口实现唯一脚本运行方式

    这篇文章主要介绍了Python 通过监听端口实现唯一脚本运行方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • python根据距离和时长计算配速示例

    python根据距离和时长计算配速示例

    这篇文章主要介绍了python根据距离和时长计算配速示例,需要的朋友可以参考下
    2014-02-02
  • Python实现批量下载SMAP数据

    Python实现批量下载SMAP数据

    在科学研究和数据分析中,获取大规模的遥感数据是一个常见的任务,本文将详细为大家介绍如何利用Python实现SMAP数据的批量下载,需要的可以参考下
    2023-12-12
  • 基于Python socket的端口扫描程序实例代码

    基于Python socket的端口扫描程序实例代码

    这篇文章主要介绍了基于Python socket的端口扫描程序实例代码,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
    2018-02-02
  • 解析Mac OS下部署Pyhton的Django框架项目的过程

    解析Mac OS下部署Pyhton的Django框架项目的过程

    这篇文章主要介绍了Mac OS下部署Pyhton的Django框架项目的过程,还附带将了一个gunicorn结合Nginx来部署Django应用的方法,需要的朋友可以参考下
    2016-05-05
  • Python中将列表转化为链表的方法详解

    Python中将列表转化为链表的方法详解

    这篇文章主要介绍了Python中将列表转化为链表的方法详解,本文的主要问题是输入一组数,将其按照顺序添加到链表中,文中提供了解决思路与部分实现代码,需要的朋友可以参考下
    2023-11-11
  • 如何通过python代码根据模板修改变量生成新yaml文件

    如何通过python代码根据模板修改变量生成新yaml文件

    有些时候,需要根据一个yaml模板创建多个yaml文件实例,我们先写一个yaml文件模板,然后通过python代码修改模板中的变量,存储为一个新的yaml文件,需要配合python的库Template及ymal使用,本文给大家讲解的非常详细,需要的朋友跟随小编一起看看吧
    2023-11-11
  • 详解python中absl包的使用

    详解python中absl包的使用

    "absl" 是 Google 开发的一个 Python 软件包,用于提供一些常见的 Python 编程功能和工具,以改善代码的可读性、可维护性和性能,下面我们就来看看absl包的具体使用吧
    2023-11-11
  • Python爬虫使用浏览器cookies:browsercookie过程解析

    Python爬虫使用浏览器cookies:browsercookie过程解析

    这篇文章主要介绍了Python爬虫使用浏览器cookies:browsercookie,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10

最新评论