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

发布时间 - 2026-01-11 00:55:54    点击率:

这两天学习了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抓取网页内容  # python抓取网页数据  # 利用Python3分析sitemap.xml并抓取导出全站链接详解  # 详解python3百度指数抓取实例  # Python3使用requests包抓取并保存网页源码的方法  # 使用Python3编写抓取网页和只抓网页图片的脚本  # python3抓取中文网页的方法  # 在Python3中使用asyncio库进行快速数据抓取的教程  # Python使用lxml模块和Requests模块抓取HTML页面的教程  # 用Python程序抓取网页的HTML信息的一个小实例  # python抓取并保存html页面时乱码问题的解决方法  # Python使用urllib2模块抓取HTML页面资源的实例分享  # Python3实现抓取javascript动态生成的html网页功能示例  # 种方法  # 这两天  # 最简单  # 大家多多  # 发现了  # NT  # Windows  # email  # act  # values  # MSIE  # user_agent  # php  # login  # compatible  # Mozilla  # yzhang  # decode  # print  # www 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 齐河建站公司:营销型网站建设与SEO优化双核驱动策略  Laravel怎么自定义错误页面_Laravel修改404和500页面模板  网站制作软件免费下载安装,有哪些免费下载的软件网站?  Laravel如何实现API版本控制_Laravel API版本化路由设计策略  Win11怎么开启自动HDR画质_Windows11显示设置HDR选项  微信小程序 五星评分(包括半颗星评分)实例代码  node.js报错:Cannot find module 'ejs'的解决办法  如何实现javascript表单验证_正则表达式有哪些实用技巧  Laravel如何实现邮件验证激活账户_Laravel内置MustVerifyEmail接口配置【步骤】  如何续费美橙建站之星域名及服务?  Laravel如何使用Socialite实现第三方登录?(微信/GitHub示例)  使用C语言编写圣诞表白程序  如何在香港服务器上快速搭建免备案网站?  长沙企业网站制作哪家好,长沙水业集团官方网站?  如何在宝塔面板创建新站点?  如何快速上传建站程序避免常见错误?  Laravel如何为API编写文档_Laravel API文档生成与维护方法  Laravel Eloquent访问器与修改器是什么_Laravel Accessors & Mutators数据处理技巧  CSS3怎么给轮播图加过渡动画_transition加transform实现【技巧】  Laravel如何配置Horizon来管理队列?(安装和使用)  在centOS 7安装mysql 5.7的详细教程  mc皮肤壁纸制作器,苹果平板怎么设置自己想要的壁纸我的世界?  宙斯浏览器文件分类查看教程 快速筛选视频文档与图片方法  零服务器AI建站解决方案:快速部署与云端平台低成本实践  Laravel Eloquent:优雅地将关联模型字段扁平化到主模型中  如何在阿里云域名上完成建站全流程?  HTML透明颜色代码怎么让图片透明_给img元素加透明色的技巧【方法】  如何用wdcp快速搭建高效网站?  儿童网站界面设计图片,中国少年儿童教育网站-怎么去注册?  如何快速生成凡客建站的专业级图册?  如何在沈阳梯子盘古建站优化SEO排名与功能模块?  Laravel集合Collection怎么用_Laravel集合常用函数详解  历史网站制作软件,华为如何找回被删除的网站?  音乐网站服务器如何优化API响应速度?  如何在HTML表单中获取用户输入并结合JavaScript动态控制复利计算循环  BootStrap整体框架之基础布局组件  如何在阿里云虚拟主机上快速搭建个人网站?  Laravel Eloquent关联是什么_Laravel模型一对一与一对多关系精讲  Laravel Fortify是什么,和Jetstream有什么关系  JS中使用new Date(str)创建时间对象不兼容firefox和ie的解决方法(两种)  如何用IIS7快速搭建并优化网站站点?  javascript日期怎么处理_如何格式化输出  Laravel怎么做缓存_Laravel Cache系统提升应用速度的策略与技巧  新三国志曹操传主线渭水交兵攻略  Laravel如何使用查询构建器?(Query Builder高级用法)  东莞专业网站制作公司有哪些,东莞招聘网站哪个好?  Laravel路由Route怎么设置_Laravel基础路由定义与参数传递规则【详解】  长沙做网站要多少钱,长沙国安网络怎么样?  百度浏览器网页无法复制文字怎么办 百度浏览器复制修复  Laravel中的withCount方法怎么高效统计关联模型数量