程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python开发爬虫的常用技术架构(python常用爬虫模块)

hfteth 2025-06-13 13:25:47 技术文章 4 ℃

爬虫(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,他提供了界面,管理爬虫。



参考资料

  1. Wireshark https://www.wireshark.org/
  2. WinPcap https://www.winpcap.org/
  3. Http https://www.rfc-editor.org/rfc/rfc2616.pdf
  4. 文小言、bito、豆包

Tags:

最近发表
标签列表