Dan*_*_DD 3 python selenium web-scraping instagram selenium-webdriver
我正在使用 Selenium 和 Python 在 Instagram 上测试一些网页抓取。
在这种情况下,我想上传一张图片。
通常,您必须单击上传图标并从窗口中选择文件。如何使用 Selenium 管理它?
我试过:
driver.find_element_by_class_name("coreSpriteFeedCreation").send_keys('C:\\path-to-file\\file.jpg')
Run Code Online (Sandbox Code Playgroud)
还有,find_element_by_xpath但我有一个例外:
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element
Run Code Online (Sandbox Code Playgroud)
我也只尝试过,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()
Run Code Online (Sandbox Code Playgroud)
现在出现选择文件的窗口。问题是我想避开这个窗口并直接给出我的文件的路径。
如果理解正确,您将试图避免使用本机窗口进行处理。你可以试试这个:
# get all inputs
inputs = driver.find_elements_by_xpath("//input[@accept = 'image/jpeg']").send_keys(os.getcwd() + "/image.png")
Run Code Online (Sandbox Code Playgroud)
现在您可以尝试所有这些。我不知道他们中的哪一个会起作用。
更多关于os.getcwd()在这里
为了能够执行此代码,您必须拥有这样的元素:
<input type="file" name="fileToUpload" id="fileToUpload2" class="fileToUpload">
Run Code Online (Sandbox Code Playgroud)
编辑:
看起来像是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")
Run Code Online (Sandbox Code Playgroud)