How to upload an image in "read only" input field - selenium

I need to upload an image in a read only input field. The code below works, but takes image url as a text file.
FYI - swf_creative is pointing to the config file where the url image is saved. The url is:
swf_creative=/Testing/creatives/Contemp.swf
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('fileName').value=\"" + swf_creative +"\"");
Screenshot:

Related

Acess data image url when the data url is only obtain upon rendering

I would like to automatically get images saved as browser's data after the page renders, using their corresponding data URLs.
For example:
You can go to the webpage: https://en.wikipedia.org/wiki/Truck
Using the WebInspector from Firefox pick the first thumbnail image on the right.
Now on the Inspector tab, right click over the img tag, go to Copy and press "Image Data-URL"
Open a new tab, paste and enter to see the image from the data URL.
Notice that the data URL is not available on the page source. On the website I want to scrape, the images are rendered after passing through a php script. The server returns a 404 response if the images try to be accessed directly with the src tag attribute.
I believe it should be possible to list the data URLs of the images rendered by the website and download them, however I was unable to find a way to do it.
I normally scrape using selenium webdriver with Firefox coded in python, but any solution would be welcome.
I managed to work out a solution using chrome webdriver with CORS disabled as with Firefox I could not find a cli argument to disable it.
The solution executes some javascript to redraw the image on a new canvas element and then use toDataURL method to get the data url. To save the image I convert the base64 data to binary data and save it as png.
This apparently solved the issue in my use case.
Code to get first truck image
from binascii import a2b_base64
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-web-security")
chrome_options.add_argument("--disable-site-isolation-trials")
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://en.wikipedia.org/wiki/Truck")
img = driver.find_element_by_xpath("/html/body/div[3]/div[3]"
"/div[5]/div[1]/div[4]/div"
"/a/img")
img_base64 = driver.execute_script(
"""
const img = arguments[0];
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
data_url = canvas.toDataURL('image/png');
return data_url
""",
img)
binary_data = a2b_base64(img_base64.split(',')[1])
with open('image.png', 'wb') as save_img:
save_img.write(binary_data)
Also, I found that the data url that you get with the procedure described in my question, was generated by the Firefox web inspector on request, so it should not be possible to get a list of data urls (that are not within the page source) as I first thought.
BeautifulSoup is the best library to use for such problem statements. When u wanna retrieve data from any website, u can blindly use BeautifulSoup as it is faster than selenium. BeautifulSoup just takes around 10 seconds to complete this task, whereas selenium would approximately take 15-20 seconds to complete the same task, so it is better to use BeautifulSoup. Here is how u do it using BeautifulSoup:
from bs4 import BeautifulSoup
import requests
import time
st = time.time()
src = requests.get('https://en.wikipedia.org/wiki/Truck').text
soup = BeautifulSoup(src,'html.parser')
divs = soup.find_all('div',class_ = "thumbinner")
count = 1
for x in divs:
url = x.a.img['srcset']
url = url.split('1.5x,')[-1]
url = url.split('2x')[0]
url = "https:" + url
url = url.replace(" ","")
path = f"D:\\Truck_Img_{count}.png"
response = requests.get(url)
file = open(path, "wb")
file.write(response.content)
file.close()
count+=1
print(f"Execution Time = {time.time()-st} seconds")
Output:
Execution Time = 9.65831208229065 seconds
29 Images. Here is the first image:
Hope that this helps!

File upload using selenium Web driver?

WebElement product_image = driver.findElement(By.id("pdt_upload_preview"));
System.out.println("-------Product image selected----------\n-----------------------");
product_image.click();
product_image.sendKeys("C:\\TEST\\TEST\\Images\\Images(1).jpg");
I can't upload the file by using this.
I hope no need to click, simply try
WebElement product_image = driver.findElement(By.id("pdt_upload_preview"));
product_image.sendKeys("C:\\TEST\\TEST\\Images\\Images(1).jpg");
If your code isn't working, it's possible that your image upload element is hidden. You could try executing Javascript to reveal the element:
WebElement product_image = driver.findElement(By.id("pdt_upload_preview"));
// execute javascript to reveal the element
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].style.display = 'block';", product_image);
// send keys to the element
product_image.sendKeys("C:\\TEST\\TEST\\Images\\Images(1).jpg");

Selenium: How to assert that image is displayed under a certain section of a webpage

I am attempting to write a test that is able to do the following:
1. Navigate to a website.
2. Navigate to a page under the menu.
3. Once in that page, assert that the image I want is displayed under a section labeled "SECTION".
Here is my code (approach 1):
public void test1() throws Exception {
WebElement compare_image = driver.findElement(By.linkText("URL link where the image is located"));
driver.get("website URL");
WebElement image = driver.findElement(By.cssSelector("cssSelector for image from FireFox -> inspect element -> copy CSS selector"));
assertEquals(image, compare_image); }
I am very new to Selenium and QA automation, so any detailed help would be appreciated as my google searches so far are coming up short. It is giving me an element not present exception for the findElement call, but I don't know why as I tried all the Bys I could get from inspect element.
Am I approaching this correctly? If not, what can I do differently?
If you want to check image is present or not under a section then you have to create a webelement for that section.
WebElement section= driver.findElement(By.xpath("//img(#class=‘Section')"));
Now create an image element under section element.
WebElement image= section.findElement(By.xpath("//img(#class=‘Test Image')"));
Now check image is exist or not.
boolean imagePresent = image.isDisplayed();
Now assert on boolean result.
assertTrue(imagePresent, “No image is exist”);
Note: Please take care of locators for section and Image as you didn’t provide Html for it. Code will work perfectly.

How to upload file using selenium webdriver for invisible element

I am unable to upload file using webdriver can you please help me.
I need to upload cover letter and resume my webpage. .
I have tried with code:
myTestDriver.findElement(By.id("uploadcover")).sendKeys("C:\\Users\\hadmin\\Desktop\\test.doc");
myTestDriver.findElement(By.id("uploadresumeimg")).sendKeys("C:\\Users\\hadmin\\Desktop\\test.doc");
But it is not working, Please give me solution.
Make invisible element visible:
String js = "arguments[0].style.visibility = 'visible'; arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0].style.opacity = 1;";
((JavascriptExecutor) driver).executeScript(js, elem);
from: selenium faq Q:Does WebDriver support file uploads?

How to verify if the image in Selenium using Webdriver

How would I verify the image is displaying is the correct path/name in Selenium using WebDriver?
I started using this code but not sure :
string _active = "<img style="display: ;" alt="Active" src="../App_Themes/Default/images/check.png"/>";
driver.FindElement(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_AddeCardControl1_gv']/tbody/tr[11]/td[7]/img")).Text.Contains(_active);
I would like to clarify to you that this code
driver.FindElement(By.XPath("//*[#id='ctl00_ContentPlaceHolder1_AddeCardControl1_gv']/tbody/tr[11]/td[7]/img")).Text.Contains(_active);
does not give you the html code for the image tag but a IWebElement object. And you can read the various attributes of this WebElement by using the GetAttribute method.
You will have to get the src attribute of the img tag you are looking for by locating the image(webelement) by xpath and then
IWebElement element = driver.FindElement(By.XPath("Your xpath"));
string path = element.GetAttribute("src");
Now you can verify the path of your image. Hope this helps you.