
爬虫常用的协议有HTTP、HTTPS、FTP、SFTP等。下面会逐个介绍这些协议的特点,并提供简单的示例代码。
1、HTTP(超文本传输协议):是一种用于传输超媒体文档的应用层协议,常用于Web应用中。Python中,可以使用requests库来发送HTTP请求。
示例代码:
import requests
url = "http://example.com"
response = requests.get(url)
print(response.text)
2、HTTPS(HTTP安全协议):是HTTP的安全版,使用了SSL/TLS协议进行加密通信。Python中,可以使用requests库来发送HTTPS请求,与HTTP请求的代码基本相同。
示例代码:
import requests
url = "https://example.com"
response = requests.get(url)
print(response.text)
3、FTP(文件传输协议):用于在网络上进行文件传输的标准协议。Python中,可以使用ftplib模块来进行FTP操作。
示例代码:
from ftplib import FTP
ftp = FTP("example.com")
ftp.login("username", "password")
ftp.cwd("path/to/directory")
files = ftp.nlst()
print(files)
ftp.quit()
4、SFTP(安全文件传输协议):是FTP的安全版,使用了加密通信。Python中,可以使用paramiko库来进行SFTP操作。
示例代码:
import paramiko
hostname = "example.com"
username = "username"
password = "password"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username=username, password=password)
sftp = ssh.open_sftp()
files = sftp.listdir(remote_path="/path/to/directory")
print(files)
sftp.close()
ssh.close()
以上是常用的爬虫协议的简单介绍和示例代码,可以根据需要选择适合的协议和相应的Python库来进行网络数据抓取。
1423

被折叠的 条评论
为什么被折叠?



