网站首页 > 技术文章 正文
爬虫(Web Crawler 或 Web Spider)是一种自动化程序,用于浏览互联网上的网页,并根据一定的规则自动抓取网页内容。爬虫的主要功能是从一个或多个起始网址开始,通过解析网页内容找到新的链接,然后继续访问这些新链接,从而遍历整个网站或者互联网的一部分。爬虫广泛应用于搜索引擎、数据挖掘、信息检索等领域。
1 基础知识
互联网上用来发布信息主要有两种,一种是基于WEB浏览器的网页,还有一种是基于各类操作系统平台的客户端应用。
因为WEB发展迅速,相关通讯协议基本都向HTTP靠齐,所以要获取信息HTTP需要有一定了解。而浏览器和WEB服务器作为主流使用HTTP协议通讯的客户端和服务端,也应该略有了解,便于识别哪些是合法访问,以及如何获得用户看到的数据。
另一部分基于Android、iOS、HarmonyOS、WIndows、Linux等操作系统的应用,这类则需要了解操作系统的SDK或者TCP/IP协议。对于一些私有协议,可以使用类似网络嗅探的方式去获取,可参考Wireshark、Winpcap之类的软件产品或者开发库。而对于大部分应用基本还是基于HTTP的协议。
如果要加快采集、分析、存储数据的速度,需要并行计算。所以线程、进程的概念要有一定的掌握。另外python提供了异步机制,能很好的解耦各个阶段的实现逻辑,所以异步机制和异步编程框架要有了解。包括asyncio和twist框架,如:
import asyncio
async def read_file(file_path):
with open(file_path, 'r') as f:
return f.read()
async def main():
file_content = await read_file('example.txt')
print(file_content)
asyncio.run(main())
获取数据
python3对http的库有内置的urllib,也有第外部组件库urllib3、request。可以较方便地通过url访问http服务。期中request会默认管理http头和cookie,urllib3则不会,使用中要特别注意下(可能相同的url,有不同的返回值)。
import sys
def test_urllib(url):
import urllib.request
targetUrl = 'https://www.baidu.com'
if url is not None and url.startswith('http'):
targetUrl = url
print(targetUrl)
response = urllib.request.urlopen(targetUrl)
html = response.read()
print(html)
def test_urllib3(url):
import urllib3
targetUrl = 'https://www.baidu.com'
if url is not None and url.startswith('http'):
targetUrl = url
http = urllib3.PoolManager()
response = http.request('GET', targetUrl)
html = response.data
print(html)
print(len(sys.argv))
for i, arg in enumerate(sys.argv):
print(f"{i}: {arg}")
url = arg
if url is not None and url.startswith('http'):
test_urllib(arg)
test_urllib3(arg)
对于一些非http协议的,需要个案考虑。这里不展开,但是可考虑一个并行框架twist,可帮助管理并发任务,提高开发效率。例如我们可以用twsit很轻松开发一个client和sever程序。
# server.py
from twisted.internet import protocol, reactor
from twisted.protocols import basic
class Echo(basic.LineReceiver):
def connectionMade(self):
self.sendLine(b'Welcome to the Twisted Echo Server!')
def lineReceived(self, line):
self.sendLine(line) # Echo back the received line
class EchoFactory(protocol.Factory):
def buildProtocol(self, addr):
return Echo()
if __name__ == '__main__':
port = 8000
reactor.listenTCP(port, EchoFactory())
print(f'Server running on port {port}...')
reactor.run()
# client.py
from twisted.internet import reactor, protocol
from twisted.protocols import basic
class EchoClient(basic.LineReceiver):
def connectionMade(self):
self.sendLine(b'Hello, Server!')
def lineReceived(self, line):
print(f'Received from server: {line.decode()}')
self.transport.loseConnection() # Close the connection after receiving data
class EchoClientFactory(protocol.ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print(f'Connection failed: {reason}')
reactor.stop()
def clientConnectionLost(self, connector, reason):
print(f'Connection lost: {reason}')
reactor.stop()
if __name__ == '__main__':
server_address = 'localhost'
server_port = 8000
factory = EchoClientFactory()
reactor.connectTCP(server_address, server_port, factory)
reactor.run()
分析数据
这里不赘述,可按照思维导图的关键字,借助aigc工具逐个学习。特别关注下xml、json解析器,在爬虫的日常工作中,这些必不可少。
存储数据
存储数据到文件可关注二进制文件,例如图片、音乐、视频等,以及办公软件如excel、word,ppt等,还有常规的标准格式文件xml和json。
数据库方面可重点掌握sqlalchemy。当然也可以直接选择与mysql、redis、mongodb匹配的库。都可组织语言问问AIGC
爬虫进阶
爬虫涉及到的技术点较多,需要分析通讯协议和模拟运行环境,甚至还要破解一些安全手段(如验证码)等。这里可重点关注端侧的模拟工具,如selenium,appnium。另外对于中继这类也很重要,学习使用fiddler之类有助于分析通讯协议,和明确数据获取的目的。
使用框架
总体来说框架的选择较简单,因为scrapy发展的很好。但是如果只是小试牛刀,可以考虑简单的框架,如crawley,他提供了界面,管理爬虫。
参考资料
- Wireshark https://www.wireshark.org/
- WinPcap https://www.winpcap.org/
- Http https://www.rfc-editor.org/rfc/rfc2616.pdf
- 文小言、bito、豆包
猜你喜欢
- 2025-06-13 ScalersTalk 成长会 Python 小组第 9 周学习笔记
- 2025-06-13 python yield -- 生成器(python3 生成器)
- 2025-06-13 Python开发必备:自定义JSON编码器完全指南
- 2025-06-13 [868]ScalersTalk成长会Python小组第16周学习笔记
- 2025-06-13 基于 Python 的 PLC 监控系统深度开发
- 2025-06-13 用Python演示ARP攻击的过程及应对办法
- 2025-06-13 Python语言有哪些特点 怎么能学好Scrapy框架
- 2025-06-13 蓝桥杯备考冲刺必刷题(Python) | 143 饮料换购
- 2025-06-13 轻松转换:Python程序将文本转为摩尔斯电码
- 2025-06-13 python 中如何针对于各种文件类型进行加密?
- 266℃Python短文,Python中的嵌套条件语句(六)
- 265℃python笔记:for循环嵌套。end=""的作用,图形打印
- 264℃PythonNet:实现Python与.Net代码相互调用!
- 259℃Python实现字符串小写转大写并写入文件
- 258℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 118℃原来2025是完美的平方年,一起探索六种平方的算吧
- 98℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 92℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
-
- Python中怎么给属性增加类型检查或合法性验证?
- 如何把python绘制的动态图形保存为gif文件或视频
- Python XOR异或 操作(python异或函数)
- 每天学点Python知识:使用制表符或换行符来添加空白
- Python3+ 变量命名全攻略:PEP8 规范 + 官方禁忌 + 实战技巧,全搞懂!
- python之类的定义和对象创建篇(如何在python中定义一个属于对象的数据成员?)
- Python函数调用常见的8个错误及解决方案
- Python学不会来打我(30)python模块与包详解
- 《防秃指南:Python高频考点串烧(附翻车现场实录)》
- Python 面向对象:掌握类的继承与组合,让你的代码更高效!
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)