Python爬虫:使用Selenium和BeautifulSoup抓取网页视频和音频
import time
from selenium import webdriver
import requests
import os
import json
from moviepy.editor import VideoFileClip, AudioFileClip
from bs4 import BeautifulSoup
# 定义目标网页的URL
url = 'https://www.1819ys.com/movie/45620-0-0.html'
# 设置chromedriver的路径
chromedriver_path = 'path/to/chromedriver' # 需要提前下载并指定chromedriver的路径
# 使用Selenium打开网页
driver = webdriver.Chrome(chromedriver_path)
driver.get(url)
# 等待网页加载完成
time.sleep(5)
# 解析网页内容
soup = BeautifulSoup(driver.page_source, 'html.parser')
# 找到所有视频和音频的链接
video_links = soup.select('a[href$='.mp4']')
audio_links = soup.select('a[href$='.mp3']')
# 下载视频和音频文件
for link in video_links:
video_url = link['href']
video_title = link.text
video_response = requests.get(video_url)
with open(f'{video_title}.mp4', 'wb') as f:
f.write(video_response.content)
for link in audio_links:
audio_url = link['href']
audio_title = link.text
audio_response = requests.get(audio_url)
with open(f'{audio_title}.mp3', 'wb') as f:
f.write(audio_response.content)
# 关闭浏览器
driver.quit()
代码解释:
-
导入必要的库:
time: 用于设置等待时间。selenium: 用于控制浏览器进行网页操作。requests: 用于下载文件。os: 用于处理文件路径。json: 用于处理 JSON 数据。moviepy.editor: 用于处理视频和音频文件(如果需要)。bs4: 用于解析网页内容。
-
定义目标网页的URL。
-
设置chromedriver的路径:
- 需要提前下载与浏览器版本对应的chromedriver,并将路径指定给
chromedriver_path变量。
- 需要提前下载与浏览器版本对应的chromedriver,并将路径指定给
-
使用Selenium打开网页:
- 使用
webdriver.Chrome()方法创建一个 Chrome 浏览器实例,并将 chromedriver 的路径作为参数传入。 - 使用
driver.get()方法打开目标网页。
- 使用
-
等待网页加载完成:
- 使用
time.sleep()方法设置等待时间,确保网页内容加载完整。
- 使用
-
解析网页内容:
- 使用
BeautifulSoup解析网页源代码,并使用 CSS 选择器找到所有视频和音频的链接。
- 使用
-
下载视频和音频文件:
- 遍历所有链接,使用
requests.get()方法下载文件,并保存到本地。
- 遍历所有链接,使用
-
关闭浏览器:
- 使用
driver.quit()方法关闭浏览器。
- 使用
错误分析:
错误信息:selenium.common.exceptions.NoSuchDriverException: Message: Unable to obtain chromedriver using Selenium Manager; 'str' object has no attribute 'capabilities'...
原因:
在实例化Chrome浏览器驱动时,传递给 webdriver.Chrome() 方法的参数应该是chromedriver的路径,而不是字符串 'path/to/chromedriver'。
解决方案:
将 chromedriver_path 变量的值替换为实际的chromedriver路径。
原文地址: https://www.cveoy.top/t/topic/fQ7v 著作权归作者所有。请勿转载和采集!