python - 使用 Selenium 和 python 为 Instagram 提供上传文件路径

标签 python selenium selenium-webdriver web-scraping instagram

我正在使用 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/

相关文章:

c# - 使用 selenium C# 在文本字段上执行键盘敲击 "Ctrl + A" "Ctrl + C"和 "Ctrl + V"#

python - 如何使用 rPython 将参数从 R 输入到 Python?

python - 名称错误 : global name 'xrange' is not defined in Python 3

javascript - Seleniumexecute_script 将 "AI"添加到函数中

selenium - 如何使用java在Selenium webdriver中按 "ALT+T"。我想通过按它来切换选项卡

java - 如何使用命令 "[javac] error: invalid target release: 12.0.1"解决 "ant run"

python - 使用 mysqyl-python 连接器时出现 SSL 连接错误

python - 为什么这个 makefile 最后会删除两个 .c 文件?

python - 抓取 Google Play 商店 BeautifulSoup/Selenium

ios - 使用 Selenium 和 ios-driver 从 Windows 计算机测试 iOS 移动应用程序