尝试将图像发送到输入时“出现问题”

问题描述 投票:0回答:1

我正在尝试使用 Selenium 和 Python 在 Instagram 上发帖。但是当我尝试将图像发送到输入站点时仅显示错误。我该如何解决这个问题?

Frame that says

进口:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
import pickle

代码:

driver.get("https://www.instagram.com/name/")
time.sleep(5)
post = driver.find_element(By.XPATH, "(//div[@class='x1n2onr6'])[9]")
post.click()
time.sleep(5)
file_input = driver.find_element(By.XPATH, "//input[@type='file' and contains(@class,'_ac69')]")
file_path = "C:\py\placeholder.jpg"  
file_input.send_keys(file_path)
time.sleep(5)

我尝试了几种将图像路径发送到输入的方法:使用斜杠(

/
)、使用反斜杠(
\
)和使用双反斜杠(
\\
)。我在网站上找不到文件的另一个输入,所以我只用一个输入尝试了所有这些。

我希望能够在输入中插入照片,但该网站显示错误。

python selenium-webdriver instagram
1个回答
0
投票

在尝试下面的代码之前,请确保图像上传在手动模式下正常工作

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# Path to the image file
file_path = r"C:\py\placeholder.jpg"

# Initialize the WebDriver
driver = webdriver.Chrome()

try:
    driver.get("https://www.instagram.com/")
    time.sleep(5)

    # Assuming you're already logged in
    # Locate and click the "Create Post" button
    post_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "(//div[@class='x1n2onr6'])[9]"))
    )
    post_button.click()

    # Wait for the file input to appear
    file_input = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//input[@type='file']"))
    )

    # Send the file path to the input
    file_input.send_keys(file_path)

    time.sleep(5)  # Wait for the upload to process
finally:
    driver.quit()
© www.soinside.com 2019 - 2024. All rights reserved.