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


相关推荐: Laravel如何实现用户注册和登录?(Auth脚手架指南)  青岛网站建设如何选择本地服务器?  装修招标网站设计制作流程,装修招标流程?  韩国代理服务器如何选?解析IP设置技巧与跨境访问优化指南  Laravel怎么实现微信登录_Laravel Socialite第三方登录集成  如何选择可靠的免备案建站服务器?  C语言设计一个闪闪的圣诞树  html文件怎么打开证书错误_https协议的html打开提示不安全【指南】  php读取心率传感器数据怎么弄_php获取max30100的心率值【指南】  Laravel怎么集成Log日志记录_Laravel单文件与每日日志配置及自定义通道【详解】  深圳网站制作公司好吗,在深圳找工作哪个网站最好啊?  uc浏览器二维码扫描入口_uc浏览器扫码功能使用地址  如何快速查询网站的真实建站时间?  如何在建站之星绑定自定义域名?  潮流网站制作头像软件下载,适合母子的网名有哪些?  制作公司内部网站有哪些,内网如何建网站?  品牌网站制作公司有哪些,买正品品牌一般去哪个网站买?  网站页面设计需要考虑到这些问题  Laravel如何配置中间件Middleware_Laravel自定义中间件拦截请求与权限校验【步骤】  中山网站制作网页,中山新生登记系统登记流程?  黑客如何利用漏洞与弱口令入侵网站服务器?  百度浏览器ai对话怎么关 百度浏览器ai聊天窗口隐藏  PHP 实现电台节目表的智能时间匹配与今日/明日轮播逻辑  如何在IIS中新建站点并解决端口绑定冲突?  如何快速搭建高效简练网站?  Laravel路由Route怎么设置_Laravel基础路由定义与参数传递规则【详解】  如何在云主机快速搭建网站站点?  韩国网站服务器搭建指南:VPS选购、域名解析与DNS配置推荐  网站制作大概要多少钱一个,做一个平台网站大概多少钱?  javascript日期怎么处理_如何格式化输出  大学网站设计制作软件有哪些,如何将网站制作成自己app?  网站制作软件有哪些,制图软件有哪些?  Laravel Seeder填充数据教程_Laravel模型工厂Factory使用  如何在腾讯云服务器快速搭建个人网站?  php结合redis实现高并发下的抢购、秒杀功能的实例  大连企业网站制作公司,大连2025企业社保缴费网上缴费流程?  Python3.6正式版新特性预览  Laravel怎么实现模型属性转换Casting_Laravel自动将JSON字段转为数组【技巧】  如何获取上海专业网站定制建站电话?  公司网站制作需要多少钱,找人做公司网站需要多少钱?  Laravel怎么实现软删除SoftDeletes_Laravel模型回收站功能与数据恢复【步骤】  Laravel怎么返回JSON格式数据_Laravel API资源Response响应格式化【技巧】  js实现点击每个li节点,都弹出其文本值及修改  北京网站制作费用多少,建立一个公司网站的费用.有哪些部分,分别要多少钱?  如何挑选优质建站一级代理提升网站排名?  如何基于云服务器快速搭建网站及云盘系统?  Laravel如何实现邮件验证激活账户_Laravel内置MustVerifyEmail接口配置【步骤】  Laravel如何处理CORS跨域问题_Laravel项目CORS配置与解决方案  rsync同步时出现rsync: failed to set times on “xxxx”: Operation not permitted  *服务器网站为何频现安全漏洞?