我正在使用 Selenium 和 Python 在 Instagram 上测试一些网络抓取。
在这种情况下,我想上传一张图片。
通常您必须单击上传图标并从窗口中选择文件。我如何使用 Selenium 管理它?
我试过:
driver.find_element_by_class_name("coreSpriteFeedCreation").send_keys('C:\\path-to-file\\file.jpg')
还有 find_element_by_xpath
但我得到一个异常(exception):
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element
我也尝试过只使用 click()
但没有任何反应。
有什么想法吗?
编辑
感谢@homersimpson 的评论,我尝试了这个:
actions = ActionChains(driver)
element = driver.find_element_by_class_name("coreSpriteFeedCreation")
actions.move_to_element(element)
actions.click()
actions.send_keys('C:\\path-to-file\\file.jpg')
actions.perform()
现在出现选择文件的窗口。问题是我想避开这个窗口并直接给出我的文件的路径。
最佳答案
如果理解正确,您正试图避免使用 native 窗口进行处理。你可以试试这个:
# get all inputs
inputs = driver.find_elements_by_xpath("//input[@accept = 'image/jpeg']").send_keys(os.getcwd() + "/image.png")
现在您可以尝试所有这些。我不知道它们中的哪一个会起作用。
关于 os.getcwd()
的更多信息是 here
为了能够执行此代码,您必须具有如下元素:
<input type="file" name="fileToUpload" id="fileToUpload2" class="fileToUpload">
编辑:
它看起来像 instagram
变成了帖子的输入字段交互。对于帐户图片,它仍然有效,但不适用于发布。我认为这样做是为了防止机器人发布图片。不管怎样,这个问题是有解决办法的。您可以像这样使用 AutoIt:
import autoit
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
ActionChains(driver).move_to_element( driver.find_element_by_xpath("//path/to/upload/button")).click().perform()
handle = "[CLASS:#32770; TITLE:Open]"
autoit.win_wait(handle, 60)
autoit.control_set_text(handle, "Edit1", "\\file\\path")
autoit.control_click(handle, "Button1")
关于python - 使用 Selenium 和 python 为 Instagram 提供上传文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50911887/