select 来自网络驱动程序文件夹的随机图像
select random images from a folder for webdriver
我想上传一张图片到 Twitter,我正在使用 selenium
我有一个包含所有图像的文件夹,但我需要在该文件夹中选择一个随机图像
感谢您的帮助
path_image = ('C:/Users/92/Desktop/python/V2/images/')
element = driver.find_element_by_xpath("//input[@type='file']")
driver.execute_script("arguments[0].style.display = 'block';", element)
element.send_keys(random.choice(path_image))
我遇到的错误
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: File not found : D
(Session info: chrome=88.0.4324.190)
当您执行 random.choice(path)
时,它会 return 您提供的路径中的一个随机字符,而不是图像文件夹中图像的路径,因为 choice()
方法需要一个列表.
您首先需要列出文件夹中的图像:
import os
images = [os.path.join(path_image, f) for f in os.listdir(path_image)]
然后在该列表中随机选择一张图片:
random.choice(images)
我想上传一张图片到 Twitter,我正在使用 selenium
我有一个包含所有图像的文件夹,但我需要在该文件夹中选择一个随机图像
感谢您的帮助
path_image = ('C:/Users/92/Desktop/python/V2/images/')
element = driver.find_element_by_xpath("//input[@type='file']")
driver.execute_script("arguments[0].style.display = 'block';", element)
element.send_keys(random.choice(path_image))
我遇到的错误
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: File not found : D
(Session info: chrome=88.0.4324.190)
当您执行 random.choice(path)
时,它会 return 您提供的路径中的一个随机字符,而不是图像文件夹中图像的路径,因为 choice()
方法需要一个列表.
您首先需要列出文件夹中的图像:
import os
images = [os.path.join(path_image, f) for f in os.listdir(path_image)]
然后在该列表中随机选择一张图片:
random.choice(images)