简体   繁体   中英

How do I right-click on an image and Copy image address using selenium C#?

How do I right-click on an image and Copy image address using selenium C#?

I used this code:

var productimgs = driver.FindElement(By.XPath("//*[@id='coconut-baby-organic']/div[1]/div[1]/div/a/div/img"));
            Actions action = new Actions(driver);
            action.ContextClick(productimgs).Build().Perform();
            action.SendKeys(Keys.ArrowDown).Build().Perform();
            action.SendKeys(Keys.ArrowDown).Build().Perform();
            action.SendKeys(Keys.ArrowDown).Build().Perform();
            action.SendKeys(Keys.ArrowDown).Build().Perform();
            action.SendKeys(Keys.Enter).Build().Perform();

I expect it to right-click on the image and keep going down till it finds "Copy image address" then click it but it's not.

This is a known issue in the Chrome Selenium Web driver.

Alternatives:

  1. Use Firebox web driver.

  2. You can achieve a similar functionality, using the inputsimulator . Note: The Chrome window must be in focus.

     // find the element and click on it. IWebElement element = driver.FindElement(By.XPath("some_xpath")); Actions action = new Actions(driver); action.ContextClick(element).Build().Perform(); // navigate in menu var input = new InputSimulator(); input.Keyboard.KeyPress(VirtualKeyCode.DOWN); input.Keyboard.KeyPress(VirtualKeyCode.DOWN); input.Keyboard.KeyPress(VirtualKeyCode.DOWN); input.Keyboard.KeyPress(VirtualKeyCode.DOWN); input.Keyboard.KeyPress(VirtualKeyCode.RETURN);

Why on earth you want to do this using context click? The approach will require browser constantly being in focus, it means that you will not be able to do anything else with your computer while the test is running, neither you will be able to run your Selenium tests in parallel mode .

Instead I would recommend fetching src attribute of the <img> tag - that would be the URL you're looking for. It can be done via IWebElement.GetAttribute() function

Example code:

var productimgs = driver.FindElement(By.XPath("//*[@id='coconut-baby-organic']/div[1]/div[1]/div/a/div/img"));
var src = productimgs.GetAttribute("src");
Console.WriteLine("Image URL is: " + src);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM