Python Selenium从Unique id下载文件

2024-04-28 11:32:31 发布

您现在位置:Python中文网/ 问答频道 /正文

希望有人会对如何做到这一点有一些想法

我刚开始学习Selenium,有一项非常具体的任务要完成。我将一种格式的文件上传到一个免费的在线服务,该服务将其转换为另一种格式,并将我重定向到一个页面,在那里我可以下载转换后的文件,但我必须单击按钮或链接才能做到这一点。(对于记录,我不能使用转换器来执行此操作,因为服务将信息添加到文件中,而不仅仅是转换文件类型)

问题是,包含转换文件的页面的URL是通用URL (例如https://www.something.com/convert?output)当我试图让Selenium在那里搜索一个文件时,它只会转到没有输出的通用链接,而不是停留在文件的重定向页面上

我知道有一个选项可以让驱动程序等待页面加载,然后继续执行任务,但据我所知,它仍然需要一个新的URL,它的结果也一样

有人知道怎么做吗

这是我当前的代码:

from selenium import webdriver

options = webdriver.ChromeOptions()

preferences = {"download.default_directory": "/home/marko/files"}

options.add_experimental_option("prefs", preferences)

driver = webdriver.Chrome('/home/marko/Downloads/chromedriver', chrome_options=options)

driver.get("url of the converting site")

choose_file = driver.find_element_by_name('uploaded_file_1')

file_location = "/home/marko/file.original"

choose_file.send_keys(file_location)

get_data = driver.find_element_by_xpath("//input[@value='Convert & add']").click()

driver.get("https://www.something.com/convert?output") -> here's the trouble

driver.find_element_by_partial_link_text("following link").click()

Tags: 文件urlhomegetby格式driverselenium
2条回答

为什么要提供另一个URL

<强>空白页的原因是它还没有被处理。

如果服务正在转换某些内容,则需要时间,并将自动重定向您。这背后的原因是服务器正在转换,它将自动显示输出。不要给出任何第二个链接。而不是等待重定向。您可以使用隐式等待或简单地使用“睡眠”

已经描述了隐式的使用。下面是如何使用睡眠

import time
time.sleep(4) # the time is in seconds

顺便问一下,你能提供你正在使用的链接吗?它可以帮助你更好

只需通过链接或下载按钮让web将您重定向到页面即可

您需要做的是让浏览器等待。为此,您可以使用:

  • 隐式等待driver.implicitly_wait(seconds)):这会在每次搜索项目时添加等待。当机器或连接速度较慢时特别有用
  • 显式等待(使用WaitWebDriver()):等待某个条件,直到某个超时时间。当您等待时间与页面加载的其余部分不一致的长进程时,这一点尤其有用

因此,使用显式等待,代码如下所示:

from selenium import webdriver
# New imports
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()

preferences = {"download.default_directory": "/home/marko/files"}

options.add_experimental_option("prefs", preferences)

driver = webdriver.Chrome('/home/marko/Downloads/chromedriver', chrome_options=options)

driver.get("url of the converting site")

choose_file = driver.find_element_by_name('uploaded_file_1')

file_location = "/home/marko/file.original"

choose_file.send_keys(file_location)

get_data = driver.find_element_by_xpath("//input[@value='Convert & add']").click()

# Once the process is started, wait for the element to be clickable
wait = WebDriverWait(driver, 20) # Adjust the timeout seconds to a reasonable max time for the process
element = wait.until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, 'following link')))

element.click()

您可以了解更多信息并找到更多等待条件here

相关问题 更多 >