Python开发爬虫的常用技术架构
ztj100 2025-05-26 20:19 15 浏览 0 评论
爬虫(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、豆包
相关推荐
- 10条军规:电商API从数据泄露到高可用的全链路防护
-
电商API接口避坑指南:数据安全、版本兼容与成本控制的10个教训在电商行业数字化转型中,API接口已成为连接平台、商家、用户与第三方服务的核心枢纽。然而,从数据泄露到版本冲突,从成本超支到系统崩溃,A...
- Python 文件处理在实际项目中的困难与应对策略
-
在Python项目开发,文件处理是一项基础且关键的任务。然而,在实际项目中,Python文件处理往往会面临各种各样的困难和挑战,从文件格式兼容性、编码问题,到性能瓶颈、并发访问冲突等。本文将深入...
- The Future of Manufacturing with Custom CNC Parts
-
ThefutureofmanufacturingisincreasinglybeingshapedbytheintegrationofcustomCNC(ComputerNumericalContro...
- Innovative Solutions in Custom CNC Machining
-
Inrecentyears,thelandscapeofcustomCNCmachininghasevolvedrapidly,drivenbyincreasingdemandsforprecisio...
- C#.NET serilog 详解(c# repository)
-
简介Serilog是...
- Custom CNC Machining for Small Batch Production
-
Inmodernmanufacturing,producingsmallbatchesofcustomizedpartshasbecomeanincreasinglycommondemandacros...
- Custom CNC Machining for Customized Solutions
-
Thedemandforcustomizedsolutionsinmanufacturinghasgrownsignificantly,drivenbydiverseindustryneedsandt...
- Revolutionizing Manufacturing with Custom CNC Parts
-
Understandinghowmanufacturingisevolving,especiallythroughtheuseofcustomCNCparts,canseemcomplex.Thisa...
- Breaking Boundaries with Custom CNC Parts
-
BreakingboundarieswithcustomCNCpartsinvolvesexploringhowadvancedmanufacturingtechniquesaretransformi...
- Custom CNC Parts for Aerospace Industry
-
Intherealmofaerospacemanufacturing,precisionandreliabilityareparamount.Thecomponentsthatmakeupaircra...
- Cnc machining for custom parts and components
-
UnderstandingCNCmachiningforcustompartsandcomponentsinvolvesexploringitsprocesses,advantages,andcomm...
- 洞察宇宙(十八):深入理解C语言内存管理
-
分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“深入理解C语言内存管理”...
- The Art of Crafting Custom CNC Parts
-
UnderstandingtheprocessofcreatingcustomCNCpartscanoftenbeconfusingforbeginnersandevensomeexperienced...
- Tailored Custom CNC Solutions for Automotive
-
Intheautomotiveindustry,precisionandefficiencyarecrucialforproducinghigh-qualityvehiclecomponents.Ta...
- 关于WEB服务器(.NET)一些经验累积(一)
-
以前做过技术支持,把一些遇到的问题累积保存起来,现在发出了。1.问题:未能加载文件或程序集“System.EnterpriseServices.Wrapper.dll”或它的某一个依赖项。拒绝访问。解...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 10条军规:电商API从数据泄露到高可用的全链路防护
- Python 文件处理在实际项目中的困难与应对策略
- The Future of Manufacturing with Custom CNC Parts
- Innovative Solutions in Custom CNC Machining
- C#.NET serilog 详解(c# repository)
- Custom CNC Machining for Small Batch Production
- Custom CNC Machining for Customized Solutions
- Revolutionizing Manufacturing with Custom CNC Parts
- Breaking Boundaries with Custom CNC Parts
- Custom CNC Parts for Aerospace Industry
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)