一、爬虫的基本原理爬虫通过HTTP协议与目标网站服务器通信。发送请求时,可以指定URL、请求方法(GET或POST)、请求头等。服务器根据请求返回HTML页面、JSON数据或其他格式的响应。HTML解...
爬虫通过HTTP协议与目标网站服务器通信。发送请求时,可以指定URL、请求方法(GET或POST)、请求头等。服务器根据请求返回HTML页面、JSON数据或其他格式的响应。HTML解析是通过解析HTML提取有用信息,如标题、图片、表格等。数据存储是将抓取的数据存储到文件(如CSV、JSON)、数据库(如MySQL、MongoDB)等介质中,便于后续分析。
安装必要的库:
pip install requests beautifulsoup4 lxml使用requests库获取网页内容。
import requests
# 定义目标 URL
url = "https://example.com"
# 设置请求头,伪装为浏览器访问
headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36"
}
# 发送请求
response = requests.get(url, headers=headers)使用BeautifulSoup从HTML中解析出需要的数据。
from bs4 import BeautifulSoup
# 获取响应的数据
soup = BeautifulSoup(response.text, 'html.parser')根据视频文件的URL规律,提取视频链接。
# 假设视频的URL在video标签的src属性中
video_tags = soup.find_all('video')
video_urls = [tag['src'] for tag in video_tags if 'src' in tag.attrs]使用requests下载视频文件。
import os
# 定义保存视频的文件夹
folder = "videos"
if not os.path.exists(folder): os.makedirs(folder)
# 遍历视频链接,下载视频文件
for video_url in video_urls: # 获取视频文件名 video_name = os.path.basename(video_url) # 构建完整的视频文件路径 video_path = os.path.join(folder, video_name) # 下载视频文件 video_response = requests.get(video_url) with open(video_path, 'wb') as f: f.write(video_response.content)使用json库解析JSON数据。
import json
# 假设获取到的数据是JSON格式
json_data = '{"name": "John", "age": 30}'
data = json.loads(json_data)
print(data['name']) # 输出:John通过循环遍历分页链接,获取所有分页数据。
# 假设分页链接格式为https://example.com/page/1, 2, 3, ...
for page in range(1, 4): url = f"https://example.com/page/{page}" response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') # 解析分页数据使用requests库下载文件。
import requests
# 定义文件URL
file_url = "https://example.com/file.zip"
# 设置请求头
headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36"
}
# 发送请求
response = requests.get(file_url, headers=headers)
# 设置文件保存路径
file_path = "downloaded_file.zip"
# 保存文件
with open(file_path, 'wb') as f: f.write(response.content)以下是一个完整的爬虫示例,用于爬取视频网站的视频文件。
import requests
from bs4 import BeautifulSoup
import os
def download_video(url, folder="videos"): if not os.path.exists(folder): os.makedirs(folder) response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}) soup = BeautifulSoup(response.text, 'html.parser') video_tags = soup.find_all('video') video_urls = [tag['src'] for tag in video_tags if 'src' in tag.attrs] for video_url in video_urls: video_name = os.path.basename(video_url) video_path = os.path.join(folder, video_name) video_response = requests.get(video_url) with open(video_path, 'wb') as f: f.write(video_response.content)
# 定义视频网站URL
video_url = "https://example.com"
download_video(video_url)