首页 > 解决方案 > 如何在 chrome 中单击并选择使用 selenium 和 python 下载音频文件以获取此特定链接

问题描述

我试图从 url: audio file 使用 selenium、python 和 Chrome 浏览器下载音频文件。(注意:请使用耳机,因为音频会自动播放并使用 chrome 浏览器打开文件)。

但是当我在显示下载选项的三个点上使用 Inspect 元素时,我找不到在代码中引用该元素的任何方法。那么,有没有其他方法可以按下“三个点”按钮,然后按下“下载按钮”?

下面是我为执行该操作而编写的代码。

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys


s=Service(ChromeDriverManager().install())
options = webdriver.ChromeOptions()
preferences = {'download.default_directory': 'some_path'}
options.add_experimental_option('prefs', preferences)
driver = webdriver.Chrome(service=s, options=options)
driver.maximize_window()

driver.get('https://www.valmiki.iitk.ac.in/sites/default/files/audio/1-1-1.mp3')
action = ActionChains(driver)
dot_dot_dot = driver.find_element(By.XPATH, "//video[@name='media']")
dot_dot_dot.click().perform()
# remaining code to click on the download button

标签: google-chromeselenium-webdriverdownloading-website-files

解决方案


基本上,“3 点”选项是视频元素控件的一部分,并且没有办法(我知道,无论如何)您可以将 3 点选项作为元素引用,仅仅是因为它不是一个元素。

解决方案 1(不推荐):

现在,您可以使用 Pyautogui 截取整个屏幕并检查 3 个点的图像在哪里(使用locateOnScreen方法),然后单击该位置。代码看起来像:-

import pyautogui

location_of_3dots = pyautogui.locateOnScreen(image=“ImageOf3Dots.png”, grayscale=True, confidence=0.6)
x_pos = location_of_3dots.left + (location_of_3dots.width / 2)
y_pos = location_of_3dots.top + (location_of_3dots.height / 2)

pyautogui.click(x_pos, y_pos)

…然后对弹出的下载选项重复相同的操作。

解决方案 2(推荐):

但实际上,如果您只想下载文件,那就太多了!如果单击 3 个点不是您的优先事项,那么您绝对应该尝试以下解决方案。基本上,代码在文档中创建了一个具有下载属性的锚标记,并将文件的源设置为页面上视频元素的源。然后单击该元素并在文件下载后将其从 DOM 中删除。代码看起来像这样:-

driver.get('https://www.valmiki.iitk.ac.in/sites/default/files/audio/1-1-1.mp3')

# The code to download the file

driver.execute_script(‘’’
    // Javascript Code to create the anchor tag and download the file
    let aLink = document.createElement("a");
    let videoSrc = document.querySelector("video").firstChild.src;
    aLink.href = videoSrc;
    aLink.download = "";
    aLink.click();
    aLink.remove();
’’’)

# rest of your code…

在执行代码时,会出现一个窗口来选择下载目的地和文件名。


推荐阅读