python网络爬虫常用技术

Python 网络爬虫的常用技术 本文将介绍 Python 网络爬虫的常用技术,包括请求发送与响应处理、页面解析、反爬虫应对、数据存储等内容,帮助读者全面了解 Python 网络爬虫的基本原理和实际应用。requests 提供了丰富的功能,支持设置请求头、Cookies、代理等,是网络爬虫的重要工具。Python 中常用的异步库包括 asyncio、aiohttp 等,通过异步请求处理,能够极大地提高爬取数据的效率。通过 BeautifulSoup,我们能够方便地提取页面中的信息,如标题、链接、文本内容等,是爬虫数据提取的重要工具。 阅读详情

urllib模块

urllib库是python中自带的模块,也是一个最基本的网络请求库,该模块提供了一个urlopen()方法,通过该方法指定URL发送网络请求来获取数据。

urllib 是一个收集了多个涉及 URL 的模块的包

urllib.request 打开和读取 URL

三行代码即可爬取百度首页源代码:

import urllib.request# 打开指定需要爬取的网页response=urllib.request.urlopen('http://www.baidu.com')# 或者是 # from urllib import request# response = request.urlopen('http://www.baidu.com')

# 打印网页源代码print(response.read().decode())

加入decode()是为了避免出现下图中十六进制内容

加入decode()进行解码后

下面三种本篇将不做详述

urllib.error 包含 urllib.request 抛出的异常

urllib.parse 用于解析 URL

urllib.robotparser 用于解析 robots.txt 文件

requests模块

requests模块是python中实现HTTP请求的一种方式,是第三方模块,该模块在实现HTTP请求时要比urllib模块简化很多,操作更加人性化。
以GET请求为例:

import requestsresponse = requests.get('http://www.baidu.com/')print('状态码:', response.status_code)print('请求地址:', response.url)print('头部信息:', response.headers)print('cookie信息:', response.cookies)# print('文本源码:', response.text)# print('字节流源码:', response.content)

输出结果如下:

状态码:200请求地址:http://www.baidu.com/头部信息:{'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Sun, 10 May 2020 02:43:33 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:23 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}cookie信息:<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>

这里讲解一下response.text和 response.content的区别

  • response.content是直接从网络上面抓取的数据,没有经过任何解码,所以是一个 bytes类型

  • response.text是将response.content进行解码的字符串,解码需要指定一个编码方式, requests会根据自己的猜测来判断编码的方式,所以有时候可能会猜测错误,就会导致解码产生乱码,这时候就应该使用 response.content.decode(‘utf-8’)

  • 进行手动解码

以POST请求为例​​​​​​​

import requestsdata={'word':'hello'}response = requests.post('http://www.baidu.com',data=data)print(response.content)

请求headers处理

当爬取页面由于该网页为防止恶意采集信息而使用反爬虫设置,从而拒绝用户访问,我们可以通过模拟浏览器的头部信息来进行访问,这样就能解决反爬虫设置的问题。

通过浏览器进入指定网页,右击鼠标,选中“检查”,选择“Network”,刷新页面后选择第一条信息,右侧消息头面板将显示下图中请求头部信息

例如:​​​​​​​

import requestsurl = 'https://www.bilibili.com/'headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'}response = requests.get(url, headers=headers)print(response.content.decode())

网络超时

在访问一个页面,如果该页面长时间未响应,系统就会判断该网页超时,所以无法打开网页。
例如:​​​​​​​

import requests

url = 'http://www.baidu.com'# 循环发送请求50次for a in range(0, 50):    try:       # timeout数值可根据用户当前网速,自行设置        response = requests.get(url, timeout=0.03) # 设置超时为0.03        print(response.status_code)    except Exception as e:        print('异常'+str(e)) # 打印异常信息

部分输出结果如下:

代理服务

设置代理IP可以解决不久前可以爬取的网页现在无法爬取了,然后报错——由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败的问题。

例如:​​​​​​​

import requests

# 设置代理IPproxy = {'http': '117.45.139.139:9006',         'https': '121.36.210.88:8080'         }# 发送请求url = 'https://www.baidu.com'response = requests.get(url, proxies=proxy)# 也就是说如果想取文本数据可以通过response.text# 如果想取图片,文件,则可以通过 response.content# 以字节流的形式打印网页源代码,bytes类型print(response.content.decode())# 以文本的形式打印网页源代码,为str类型print(response.text) # 默认”iso-8859-1”编码,服务器不指定的话是根据网页的响应来猜测编码。

Beautiful Soup模块

Beautiful Soup模块是一个用于HTML和XML文件中提取数据的python库。Beautiful Soup模块自动将输入的文档转换为Unicode编码,输出文档转换为UTF-8编码,你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了,然后,仅仅需要说明一下原始编码方式就可以了。

例如:​​​​​​​

from bs4 import BeautifulSoup

html_doc = """<html><head><title>The Dormouse's story</title></head><body><p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;and they lived at the bottom of a well.</p>

<p class="story">...</p>"""# 创建对象soup = BeautifulSoup(html_doc, features='lxml')# 或者创建对象打开需要解析的html文件# soup = BeautifulSoup(open('index.html'), features='lxml')print('源代码为:', soup)# 打印解析的HTML代码

运行结果如下:​​​​​​​

<html><head><title>The Dormouse's story</title></head><body><p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;and they lived at the bottom of a well.</p><p class="story">...</p></body></html>

用Beautiful Soup爬取百度首页标题​​​​​​​

from bs4 import BeautifulSoupimport requests

response = requests.get('http://news.baidu.com')soup = BeautifulSoup(response.text, features='lxml')print(soup.find('title').text)

运行结果如下:

百度新闻——海量中文资讯平台

Python经验分享

学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

Python学习路线

这里把Python常用的技术点做了整理,有各个领域的知识点汇总,可以按照上面的知识点找对应的学习资源。
在这里插入图片描述

学习软件

Python常用的开发软件,会给大家节省很多时间。
在这里插入图片描述

学习视频

编程学习一定要多多看视频,书籍和视频结合起来学习才能事半功倍。
在这里插入图片描述

100道练习题

在这里插入图片描述

实战案例

光学理论是没用的,学习编程切忌纸上谈兵,一定要动手实操,将自己学到的知识运用到实际当中。
在这里插入图片描述
最后祝大家天天进步!!

上面这份完整版的Python全套学习资料已经上传至优快云官方,朋友如果需要可以直接微信扫描下方优快云官方认证二维码免费领取【保证100%免费】。

​​​​​​​

Python网络爬虫技术详解文档 搜索引擎数据收集(Googlebot)价格监控与市场分析舆情监测与数据分析学术研究数据采集。 阅读详情

相关推荐

Python爬虫详解:原理、常用库与实战案例

1.什么是爬虫爬虫(Spider),也被称为网络爬虫或网络蜘蛛,是一种自动化程序,用于在互联网上浏览和提取信息。爬虫通过模拟人类用户访问网页的行为,从网页中提取数据并将其存储或进行进一步处理。爬虫可以自动遍历互联网上的各个网页,并根据预设的规则和算法来解析和收集感兴趣的信息。这些信息可以包括网页的文本内容、图片、链接、视频等等。爬虫可以用于很多领域,例如搜索引擎的网页索引、数据挖掘、自动化测试、价格比较、舆情监测等等。

qq_56262770的博客 5819

Python的网络爬虫框架-网络爬虫的常用技术

大家好我是ζ小菜鸡,让我们一起来学习Python的网络爬出框架-网络爬虫的常用技术(一起努力,咱们顶峰相见!!!)

精益求精,永无止境,永远在路上! 1896

Python 网络爬虫高阶用法

通过学习本文的内容,读者应掌握 Python 网络爬虫的高级用法,并能够应对反爬虫机制、抓取动态网页、实现分布式和异步爬虫。网络爬虫技术在数据抓取、信息采集等方面有着广泛的应用,掌握这些技能将大大提升数据处理和分析的效率。

好看资源网的博客 9811

【Python笔记】网络爬虫——常用技术

网络爬虫常用技术Python 的网络请求1.urllib 模块2.urllib3 模块3.requests 模块请求 headers 处理网络超时代理服务HTML解析之 BeautifulSoup1.BeautifulSoup 的安装2.BeautifulSoup 的使用 Python 的网络请求 上一节中多次提到了 URL 地址与下载网页,这两项是网络爬虫必备而又关键的功能,说道这两个功能必然离...

萌宅鹿的技术小屋 812

Python网络爬虫原理与应用

总体而言,无论是国内还是国外,Python网络爬虫技术都在不断发展和完善。国内在应用场景的拓展和实践方面取得了显著成果,而国外则在技术创新和理论研究上更具领先优势。两者相互促进,共同推动了Python网络爬虫技术的发展。然而,目前该领域仍面临一些挑战,如反爬虫机制的应对、大规模数据的高效处理等,需要进一步深入研究和探索。网络爬虫(Web Crawler),又称网络蜘蛛(Web Spider)或网络机器人(Web Robot),是一种按照一定的规则自动抓取互联网信息的程序或脚本。

m0_74752294的博客 1803

16. python从入门到精通——Python网络爬虫

网络爬虫:又被称为网络蜘蛛、网络机器人。它可以实现按照指令的规则或程序的算法自动浏览网络并且获取网络中的信息。

weixin_43812198的博客 1732

python网络爬虫_全网最全的python网络爬虫常用技术

前言urllib模块urllib库是python中自带的模块,也是一个最基本的网络请求库,该模块提供了一个urlopen()方法,通过该方法指定URL发送网络请求来获取数据。正文urllib 是一个收集了多个涉及 URL 的模块的包urllib.request 打开和读取 URL三行代码即可爬取百度首页源代码:import urllib.request# 打开指定需要爬取的网页response=u...

weixin_39710462的博客 496

别再写前端了!用Gradio 3.x + HuggingFace Spaces,5分钟把你的Python算法变成网页应用

本文介绍如何利用Gradio 3.x和HuggingFace Spaces快速将Python算法转化为网页应用,无需前端开发经验。通过5行代码和简单的Git命令,即可实现专业级Web界面部署,大幅提升算法展示效率。特别适合算法工程师和数据科学家快速分享模型成果。

weixin_33443333的博客 332

python网络爬虫技术栈

以下是Python网络爬虫常用的技术栈,以表格形式展示:RequestsBeautifulSoupSeleniumMySQLMongoDB。

WuqianZhi_123的博客 1484

角谱迭代与傅里叶变换迭代算法(GS)的原理及其实例演示分析

角谱迭代与傅里叶变换迭代算法(GS)的原理及其实例演示分析 目前,迭代法和强度传输方程(TIE)法是两类典型的非干涉相位检索技术(Phase Retrieval,被称为相位恢复、相位检索、相位反演法、相位复原等)。迭代法中的经典算法是Gerchberg-Saxton(GS),随后,出现了包括错误减少算法(ER)、混合输入输出法(HIO)、梯度搜索算法、角谱迭代算法等改进算法。...

简单光学 2万+

基于开源项目构建 CFS(网络靶场实战演练)平台

摘要:构建CFS网络靶场可使用多个开源组件组合,包括EVE-NG/GNS3或ContainerLab构建网络环境,Kasm提供工作空间,CALDERA+Atomic Red Team实现攻击模拟,DetectionLab建立防御环境,Malcolm/Arkime进行流量监控,CyRIS提供编排框架,Vulhub/DVWA创建漏洞靶标。关键在于通过API深度集成各组件,同时需注重安全隔离、资源规划及维护成本。建议开发统一管理平台,结合Ansible/Terraform实现自动化部署,打造定制化实战演练环境。(

深山技术宅的博客 1846

用python搞网络爬虫开发,你把握住了吗?(系列文章建议收藏)

网络爬虫,可以按照指定的规则(一些常见的网络爬虫算法)自动浏览或爬取网络中的信息,通过python可以轻松地编写爬虫程序或者脚本。这个系列就介绍通过python实现网络爬虫的一些基本知识和常用技术,有些专有名词对于小白来说可能不太友好,会通过具体的例子去解释这些专有名词是干什么的。

qq_45049500的博客 2301

CiteSpace关键词聚类图谱含义详细解析

CiteSpace关键词聚类图谱含义详细解析 回顾上一次推文:CiteSpace关键词共现图谱含义详细解析 其中有一句: 当你人工已经可以很容易的进行归纳后,就不需要再利用CiteSpace聚类功能啦。 我们来看一下上次推文做出来的关键词共现图谱: 人工不好归纳!那怎么聚类呢? 此时便可使用CiteSpace的聚类功能啦! 如下所示:我们可以清晰地看到上边的关键词共现网络聚成了一个个不规则区域...

qq_39974284的博客 6万+

python从入门到精通——网络爬虫开发17

一,初识网络爬虫 二,网络爬虫的常用技术 三,网络爬虫开发常用框架 四,实战项目:快手爬票

cyl16688 396

微信小程序 实现拼图功能

微信小程序 实现碎片拼图

weixin_45689786的博客 2250

Keil5调试遇坑记:手把手解决J-Link驱动与固件版本冲突(附老版本驱动包)

本文详细解析了Keil5与J-Link调试器版本冲突问题,特别是当出现'The connected J-Link is defective'警告时的解决方案。通过对比升级固件与降级驱动的优缺点,提供了详细的J-Link驱动降级操作指南,包括获取老版本驱动、替换步骤及常见问题排查,帮助开发者高效解决这一常见调试障碍。

metaverse5vr的博客 107

网络爬虫技术

本文介绍了网络爬虫的基础概念与应用。主要内容包括:1)爬虫定义与分类,分为通用、聚焦、增量式和深层网络爬虫四种类型;2)核心工作原理,涉及HTTP请求过程、响应结构和网页基础;3)常见爬取策略如宽度优先(BFS)和深度优先(DFS)遍历;4)Python中Requests库的使用方法,包括请求发送、响应处理和异常捕获。文章通过百度网页爬取实例,展示了网络爬虫从发送请求到获取响应的完整流程,为初学者提供了网络数据采集的基础知识框架。

2302_78993464的博客 2958

【图像超分】论文复现:经典超分 | SAN的Pytorch源码复现,跑通源码,适配高版本的python/pytorch/cuda,使用EDSR-PyTorch进行训练和测试

本文介绍了单幅图像超分辨率重建方法SAN(二阶注意网络)的代码实现。文章详细说明了在高版本Python/Pytorch环境下适配SAN源码的方法,并提供了修改后的完整代码和预训练模型下载链接。 主要亮点包括: 将SAN模型实现整合到EDSR-Pytorch框架中,解决了高版本环境下的兼容性问题 提供了完整的数据集准备指南(DIV2K训练集和5个测试集) 给出了详细的测试命令,涵盖x2、x3、x4不同放大倍率 公开了预训练模型和可视化结果的下载资源 提供了修改后的适配高版本环境的代码。

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 1412

《Python 网络爬虫》

本文介绍了 Python 网络爬虫的基本概念、技术原理、常用工具以及实战案例,希望能够帮助读者快速掌握 Python 网络爬虫技术。在实际应用中,需要根据具体的需求选择合适的工具和方法,并注意遵守法律法规和网站的使用条款,避免对网站造成过大的负担和影响。Scrapy 是一个功能强大的 Python 爬虫框架,它提供了一套完整的爬虫开发工具,包括请求发送、网页解析、数据存储等。网络爬虫,又称为网页蜘蛛、网络机器人,是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。(一)爬取新闻网站数据。

weixin_47266126的博客 1705

光伏微电网蓄电池储能控制系统设计及动态性能分析

本文构建了光伏微电网蓄电池储能控制系统的完整理论体系。在系统架构方面,提出了基于直流母线电压平衡的多时间尺度能量管理理论,建立了光伏发电单元的二阶物理模型和MPPT动态跟踪算法。针对蓄电池系统,设计了融合二阶RC等效电路与扩展卡尔曼滤波的SOC估计方法,误差控制在3%以内。双向DC-DC变换器采用状态空间平均建模方法,推导了小信号传递函数,为闭环控制提供理论基础。该体系实现了从瞬时功率平衡到长期能量调度的多层级协同控制,为微电网稳定运行提供了系统的解决方案。

AI的内部世界的博客 191

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Python 网络爬虫核心指南

通过结合工具链与反爬策略,可高效完成从简单页面到复杂动态网站的爬取任务。(框架,适合复杂项目)

GanKuRenSheng的博客 1354

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Python 网络爬虫技术:从基础概念到实战案例

vscode是一个微软开发的优秀的代码编辑器。vscode可以安装各种插件来拓展它的功能,安装jupyter相关的插件可以让我们在vscode中运行ipynb类型的文件。这个爬虫脚本实现了对车质网新能源汽车销量数据的爬取和存储功能。主要使用了 requests 获取网页内容,BeautifulSoup 解析 HTML,pandas 处理数据,以及 sqlalchemy 连接 MySQL 数据库。

H188693的博客 1743

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Python的那些事第十六篇:Python的网络爬虫技术

随着互联网的飞速发展,网络爬虫技术在数据采集、信息挖掘等领域发挥着重要作用。本文详细介绍了Python环境下常用的网络爬虫技术,包括Requests库、BeautifulSoup库以及Scrapy框架。通过对这些工具的使用方法、项目结构、数据提取与存储等方面的深入探讨,结合具体实例,展示了如何高效地构建网络爬虫项目,以满足不同场景下的数据采集需求。本文的研究成果为网络爬虫技术的应用提供了实践指导,同时也为相关领域的研究提供了参考。

weixin_74149145的博客 1790
上一篇: Python计算机语言中的“万金油”,那些从业者适合学Python?
下一篇: 学会Python爬虫,或许你也能月薪过万!
壹只小小码农
博客等级 码龄5年 8101粉丝 1334原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值