0

My question follows the solution of this post: Python with Selenium: Drag and Drop from file system to webdriver?

I want to use selenium to drag and drop my local image into google lens search. I followed the solution from the above post but it didn't work for me. This is the code from the previous solution:

JS_DROP_FILE = """
    var target = arguments[0],
        offsetX = arguments[1],
        offsetY = arguments[2],
        document = target.ownerDocument || document,
        window = document.defaultView || window;

    var input = document.createElement('INPUT');
    input.type = 'file';
    input.onchange = function () {
      var rect = target.getBoundingClientRect(),
          x = rect.left + (offsetX || (rect.width >> 1)),
          y = rect.top + (offsetY || (rect.height >> 1)),
          dataTransfer = { files: this.files };

      ['dragenter', 'dragover', 'drop'].forEach(function (name) {
        var evt = document.createEvent('MouseEvent');
        evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);
        evt.dataTransfer = dataTransfer;
        target.dispatchEvent(evt);
      });

      setTimeout(function () { document.body.removeChild(input); }, 25);
    };
    document.body.appendChild(input);
    return input;
"""

def drag_and_drop_file(drop_target, path):
    driver = drop_target.parent
    file_input = driver.execute_script(JS_DROP_FILE, drop_target, 0, 0)
    file_input.send_keys(path)`

Below is my code and what I got:

I really appreciate your answers!

enter image description here



# Set the local path to the image
path = 'C:/Users/ThiNgocLinhHoang/Downloads/kisspng-stihl-chainsaw-mtd-products-power-tool-string-trim-5af1860203dfb1.4390439015257779220159.png'  

# Set the Google Lens search URL with parameters for image URL and language/country
google_lens_url = f'https://www.google.com.mx/'


options = webdriver.ChromeOptions()

options.add_argument('--lang=es-MX')
options.add_experimental_option('prefs', {'intl.accept_languages': 'es-MX'})

driver = webdriver.Chrome(options=options)


# Navigate to Google Lens search page
driver.get(google_lens_url)

# Find the "Agree" button and click it
agree_button = driver.find_element(By.XPATH,'//*[@id="L2AGLb"]/div')
agree_button.click()

driver.get(google_lens_url)

driver.find_element(By.XPATH,'/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[3]/div[3]').click()
time.sleep(1)

#navigate to the drag and drop area
drop_target = driver.find_element(By.XPATH, '//*[@id="ow6"]/div[3]/c-wiz/div[2]/div/div[3]/div[2]')

#use the pre-defined drag_and_drop function
drag_and_drop_file(drop_target, path)
liquor
  • 1

0 Answers0