python 文件上传保存路径_使用Selenium和python将上传文件路径提供给Instagram

I'm testing some web scraping on Instagram with Selenium and Python.

In this case I want to upload a picture.

Normally you have to click on the upload icon and choose the file from a window. How can I manage it with Selenium?

I tried:

driver.find_element_by_class_name("coreSpriteFeedCreation").send_keys('C:\\path-to-file\\file.jpg')

and also with find_element_by_xpath but I get an exception:

selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element

I tried also only with click() but nothing happens.

Any Idea?

EDIT

Thanks to @homersimpson comment I tried this:

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()

Now the window to choose the file appears. The problem is that I would like to avoid this window and give directly the path of my file.

解决方案

If right understand, you are trying to avoid handling with a native window. You can try this:

# get all inputs

inputs = driver.find_elements_by_xpath("//input[@accept = 'image/jpeg']").send_keys(os.getcwd() + "/image.png")

Now you can try all of them. I don't know which of them will work.

More about os.getcwd() is here

To be able to perform this code you have to have an element like this:

EDIT:

It looks like instagram turned of input fields interaction for posts. For Account image it still works, but not for posting. I assume it is was done to prevent bots to post images. Anyway, there is a solution for this problem. You can use AutoIt like this:

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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值