Get HTML Source of WebElement in Selenium Webdriver using Python

Get HTML Source of WebElement in Selenium Webdriver using Python,in this lesson you will get complete selenium python code to print or get html source of webelement with the help of innerHtml attribute to get source of the content of the element or outerHtml for source with the current element.

Below is the code:


element.get_attribute('innerHTML')


import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get("http://www.python.org")
        elem = driver.find_element_by_xpath("//*")
  source_code = elem.get_attribute("outerHTML")
  

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()
 

If you want to save it to a file,use below code.
 
 
f = open('c:/htmlfile.html', 'w')
f.write(source_code.encode('utf-8'))
f.close()

Print Google Search results using Selenium in Python

Print Google Search results using Selenium in Python,below is the sample class which we can use to execute the code, you just need to change the path to webdriver as per your computer drive path. It was made for PhantomJS ,You can download it HERE., if you want to use Chrome just use 

"self.driver = webdriver.Chrome(path)".


Below is code example:


from urllib.parse import quote_plus
from selenium import webdriver


class Browser:

    def __init__(self, path, initiate=True, implicit_wait_time = 10, explicit_wait_time = 2):
        self.path = path
        if initiate:
            self.start()
        return

    def start(self):
        self.driver = webdriver.Chrome(path)
        self.driver.implicitly_wait(self.implicit_wait_time)
        return

    def end(self):
        self.driver.quit()
        return

    def go_to_url(self, url, wait_time = None):
        if wait_time is None:
            wait_time = self.explicit_wait_time
        self.driver.get(url)
        print('[*] Fetching results from: {}'.format(url))
        time.sleep(wait_time)
        return

    def get_search_url(self, query, page_num=0, per_page=10, lang='en'):
        query = quote_plus(query)
        url = 'https://www.google.hr/search?q={}&num={}&start={}&nl={}'.format(query, per_page, page_num*per_page, lang)
        return url

    def scrape(self):
        #xpath migth change in future
        links = self.driver.find_elements_by_xpath("//h3[@class='r']/a[@href]") # searches for all links insede h3 tags with class "r"
        results = []
        for link in links:
            d = {'url': link.get_attribute('href'),
                 'title': link.text}
            results.append(d)
        return results

    def search(self, query, page_num=0, per_page=10, lang='en', wait_time = None):
        if wait_time is None:
            wait_time = self.explicit_wait_time
        url = self.get_search_url(query, page_num, per_page, lang)
        self.go_to_url(url, wait_time)
        results = self.scrape()
        return results


path = '<YOUR PATH TO PHANTOMJS>/phantomjs-2.1.1-windows/bin/phantomjs.exe'## SET YOU PATH TO phantomjs
br = Browser(path)
results = br.search('site:facebook.com inurl:login')
for r in results:
    print(r)

br.end()

How to send attachments in jenkins emails

How to send attachments in Jenkins emails or Configure Jenkins to send an attachment in email using Editable Email Notification plugin in Jenkins to attach a file with the email.
With the help of Ant pattern we can send attachment in Jenkins Email.Please follow my example to send and attachment in Jenkins email.

Gmail SMTP  configurations

Enter Admin Email address as your gmail address
Default user e-mail suffix - @gmail.com
smtp.gmail.com
465
UTF-8
Use SSL Authentication
Enter gmail id
Enter password
Test Email by click on Test Email Configuration

Under Jenkins Job

Select Post Build Action as Editable Email Notifications
Under Attachment enter this format,suppose you want to get png files from Screenshot folder then
follow this format

**/Screenshot/Register.png

Suppose you want to send all png files in email then follow below format

**/Screenshot/*.png


How to configure Jenkins to send an attachment in email,
Jenkins Email-ext (Editable Email Notifications)
How to configure Jenkins to send a file as Email attachment
Jenkins pipeline email attachment
attach file from work space Jenkins


What is the default port number used by hub in Selenium?

What is the default port number used by hub in Selenium,While working with Selenium Grid,we require to configure Selenium Hub to connect to different machines and it will have default port number.

What is the default port number used by hub in Selenium?

What is the default port number used by hub in Selenium?

a. 4444
b. 2222
c. 3434
d. 2290

ANSWER : 4444

Difference Between Assertion and Verification in Selenium

In this Difference Between Assertion and Verification in Selenium post you will learn exact difference and when to use assert and verify command in selenium scripts,Selenium Verify command will not stop Test execution of Test cases if verification Test fails.

It will log an error/defect and continue with Test Cases execution of remaining  test cases. We use Selenium verify commands in Selenium IDE when you still want to proceed with Test execution of test case even if expected output is not matched for a test steps.  

Difference Between Assertion and Verification in Selenium


Selenium Assertion command will stop Test execution of Test cases if verification point fails. It will log an error/defect and will not continue with Test Cases execution of remaining Test case scripts. We can use assertions in Test scenarios where there is no point to continue further Test Execution if expected result is not matching with actual test results. 

It is very simple. You can Use assertions when you want to stop Test case execution , if expected Test results is not matched with actual test results and you can use verification points when you still want to continue test script execution of a test cases if expected test results is not matched with actual test results.

Trending Posts:

Handle Authentication using Selenium

L&T Infotech Selenium Webdriver Interview Questions

L&T Infotech Selenium Webdriver Interview Questions and Answers with examples.L&T Infotech is located in Pune and Hiring for Mumbai Location for Selenium Test Engineer with Selenium ,TestNG,Appium Mobile App Testing,Rest API testing using Soap UI skills.


 L&T Infotech Selenium Webdriver Interview Questions



L&T Infotech Selenium Webdriver Interview Questions

ALSO READ


What is the difference between list and set?

List: 

It is an Interface and it will display the list data in which order it is inserted.

Set:

Set is an interface and it will display the list values in random way not in a insertion order.If want to display in inserted order then we can go for TreeSet<> interface.

------------------------------------------------------------------------------
How will you switch to other window?

driver.switchTo().Window(window id);

or 

driver.switchTo.window(driver.getWIndowHandles.)

------------------------------------------------------------------------------
What is the return type of driver.findelement/driver.getwindowhandles()?

findElements() takes argument of type of By class and returns all the matching web elements present in currently loaded web page only. This method returns all matching web elements in a List of type WebElement which is an interface in Collection framework.

findElement() method takes argument of By class and returns first matching web element on currently loaded web page. If passed locator is matching with multiple web elements, it will return only first matching web element.

------------------------------------------------------------------------------
What is the difference between Private and Protected?

private hides from other classes within the package. public exposes to classes outside the package. protected is a version of public restricted only to subclasses.

Private

Like you'd think, only the class in which it is declared can see it.

Package Private

Can only be seen and used by the package in which it was declared. This is the default in Java.

Protected

Package Private + can be seen by subclasses or package member.

Public

Everyone can see it.
------------------------------------------------------------------------------
How will you achieve dynamic polymorphism?

Dynamic Polymorphism also called as RunTime Polymorphism.

------------------------------------------------------------------------------

What is inheritance and encapsulation?

Inheritance

Inheritance in java is one object can access all parent object properties and values from another class.


Encapsulation:

Encapsulation is nothing but binding data and code into a single unit for example package  which contains number of classes,those classes are binding together into a single package.

------------------------------------------------------------------------------
Can you override static methods?

We cannot override static methods. Static methods are belogs to class, not belongs to object. Inheritance will not be applicable for class members.

We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence the answer is ‘No’.

------------------------------------------------------------------------------
Can main method be overloaded?

Yes, you can overload main method in Java. But the program doesn't execute the overloaded main method when you run your program, you have to call the overloaded main method from the actual main method.

that means main method acts as an entry point for the java interpreter to start the execute of the application. where as a loaded main need to be called from main.

Example:

class Simple{  

  public static void main(int a){  
  System.out.println(a);  
  }  

  public static void main(String args[]){  
  System.out.println("main() method invoked");  
  main(10);  
  }  
}  


------------------------------------------------------------------------------
What is Singleton?

Singleton is a Class in Java ,which is having only one Object at a time.Singleton class purpose is to control object creation,limiting the number of objects to one object.

1.Constrctor as a private
2.Need Static method with return type object

------------------------------------------------------------------------------
What is collections in Java?

Ans:collections is a class,where Collection is an interface.
A collection is simply a object that groups multiple elements into a single unit.

-------------------------------------------------------------------------------
What is nested class?

Java Programming allow to creates a class under another class.
------------------------------------------------------------------------------
How will you call a protected method in a nested class?

In a web page, how will you ensure that page has been loaded completely?

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("return document.readyState").toString().equals("complete");

------------------------------------------------------------------------------
What is the difference between build and perform method in Actions Class?

The build() method is used compile all the listed actions into a single step.
we have to use build() when we are performing sequence of operations and no need to use only if we are performing single action.

example where build() required
Actions builder = new Actions(driver);
builder.clickAndHold((WebElement)listItems.get(0)).clickAndHold((WebElement)listItems.get(3)).click().build().perform();

in the above code we are performing more than one operations so we have to use build() to compile all the actions into a single step

example where build is not required

WebElement draggable = driver.findElement(By.id("draggable")); 
WebElement droppable = driver.findElement(By.id("droppable")); 
new Actions(driver).dragAndDrop(draggable, droppable).perform();
in the above code we are performing just a single operations so no need to use build()

------------------------------------------------------------------------------

What are different annotations in TestNG?

@BeforeSuite: The annotated method will be run before all tests in this suite have run. 
@AfterSuite: The annotated method will be run after all tests in this suite have run. 
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run. 
@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run. 
@BeforeGroups: The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked. 
@AfterGroups: The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked. 
@BeforeClass: The annotated method will be run before the first test method in the current class is invoked. 
@AfterClass: The annotated method will be run after all the test methods in the current class have been run. 
@BeforeMethod: The annotated method will be run before each test method. 
@AfterMethod: The annotated method will be run after each test method.

------------------------------------------------------------------------------
What is the difference between before method and before test?

@BeforeMethod: The annotated method will be run before each test method. 

@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run. 

------------------------------------------------------------------------------
How will you display the character count in a string "Steve Jobs" by ignoring space on between?

String test = "Steve Jobs";
System.out.println(test.replace(" ", "").length());

Replacing empty space with 0 character
------------------------------------------------------------------------------
What is a constructor and when will you use this and super in a constructor?

------------------------------------------------------------------------------
If you want to call a constructor from parent class, what will you do?

------------------------------------------------------------------------------
How will you run your tests using Data Driven Framework?

------------------------------------------------------------------------------
What are static variables and methods?

Static Variables

Variables declared with static keyword is known as Static Variables and it is a class level variables.
Static variables are shared among all the instances of class,this type of variables are useful in memory management.

Examples:

public static String username="admministrator";
public static int mobileNo="2222222222";

Static Method

Static Methods are the methods in Java that can be called without creating an object of class.They are referrenced by the class name itself .
No need to create any object to access static methods from another class .

Examples

Class 1:


public class Student{


public static String student_Name=" ";

public static void studentsNames(String name){

student_Name = name;

}

Class 2:

Accessing class 1 static method 

public class CSEStudents{

Student.studentsNames("Rajesh");
System.out.println(Student.student_Name);


//You can access student_Name method with creating object as below

Student obj = new Student();
obj.studentsNames("Kuchana");


}

}

Output:

Rajesh
Kuchana

------------------------------------------------------------------------------
How will you handle Alerts in selenium?

Alert obj = driver.switchTo.alert();
String alertText=obj.getText();

if (alertText.equals("Enter valid Username")){
obj.accept();

}else{
System.out.println("Alert is not present- giving exception");
}


-------------------------------------------------------------------------------
How will you handle a file upload window using Selenium?

There's no API for WebDriver that would allow you to work with browser dialog's,we can use below code to file uploading.

String filePath = System.getProperty("user.dir") + "/src/res/test.pdf;
 driver.findElement(By.id("elementID")).sendKeys(filePath);


------------------------------------------------------------------------------
Can I define one class into another class?

Yes ,those are nested class

two types

1.Static class
2.Inner Classes

------------------------------------------------------------------------------
What are different types of modifiers present in Java?

default
public
private
protected

------------------------------------------------------------------------------
How will you make a build using Jenkins?

1.Click on New Item in Jenkins Dashboard
2.Enter Item Name
3.Select Free Style Project
4.Click on OK
5.Enter Description 
6.Select check box Delete Build before Build Starts in Build Environment
7.Select Windows Batch Command in Build Tab

Enter Command as below to run selenium Test Scripts:

set projectpath=E:\Selenium_Practice
cd %projectpath%
set classpath=%projectpath%\bin;%projectpath%\libs\*
java org.testng.TestNG %projectpath%\testng.xml


8.Select Publish Test Results in Post-Build Actions Tab

Enter TestNG XML report pattern as " **/testng-results.xml"

9.Click on Save button


------------------------------------------------------------------------------
How will you install ReportNG in your project?


1.Download ReportNG jar files
2.Add those jar files to project build path
3.In textng.xml file add listners as below

 <listeners>
        <listener class-name="org.uncommons.reportng.HTMLReporter"/>
        <listener class-name="org.uncommons.reportng.JUnitXMLReporter"/>        
    </listeners>
------------------------------------------------------------------------------
How will you control data using XML?

We can use textng.xml file to pass the data for parameterization

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" thread-count="3" >
<parameter name="author" value="Selenium WebDriver" />
<parameter name="searchKey" value="America" />
<test name="testGuru">
<parameter name="searchKey" value="India" />
<classes>
<class name="parameters.ParameterWithTestNGXML">
</class>
</classes>
</test>
</suite>


@Test
@Parameter({"author","searchKey"})
public testing(string author,string searchKey){

 WebElement searchText = driver.findElement(By.name("q"));
        //Searching text in google text box
        searchText.sendKeys(searchKey);

        System.out.println("Welcome ->"+author+" Your search key is->"+searchKey);
}

------------------------------------------------------------------------------
How will you display a value of a particular cell in a web table?


------------------------------------------------------------------------------
How will you handle dynamic elements using XPath?

Using below two methods,we can handle dynamic elements using XPATH in Selenium Webdriver

1.Absolute path

Creating xpath for web element from root of the element to destination element as below

/html/body/div/div[1]/h1/li

2.Using contains and start-with()

driver.findElement(By.xpath(“//*[contains(@id,’username’)]”)).sendKeys(“username”);
driver.findElement(By.xpath(“//*[starts-with(@id,’user’)]”)).sendKeys(“username”);

------------------------------------------------------------------------------
What is POM?

A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects.

Example:

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-app</artifactId>
  <version>1</version>
</project>

------------------------------------------------------------------------------

Selenium Automation Testing Opening Bangalore

Greetings from US Tech Solutions,We have an immediate job opening for Automationif you are interested for below JD please revert me with following details and your updated resume tomanjula@ustechsoultionsinc.com, References are more helpful.

Role: Automation
Client: MNC Company
Job Location: Bangalore
Exp: 4+ Yrs

Key skills required for the job are:

·         Test automation with using Ruby and Cucumber (Must).
·         Automation Framework – Selenium (Must), IntellijIdea (Ruby).
·         SoapUI, REST API, Splunk, MQ Explorer(Good to have)
·         SQL (DB2) and Mongo DB, exposure to agile practices.


Please revert me with following details:

Total Exp: Yrs,
Relevant Exp: Yrs,
CCTC: Lpa,
Take Home per month:
ECTC: Lpa,
Notice Period: Days,
Current/Last Working Organization:
Pay rolling company Name:
Are you interested for Contract to Hire?
Current Location:
Preferred Location:
Full time Education:
Date of Birth:
Skype ID:
Alternative Mobile No:
Alternative Email:
Reason for looking change:


Thanks & Regards,
Manjula. Thota
Ph: 040-66309632

Software Testing Opening with Capgemini

This is opening with Capgemini for software tester.
Position type: Permanent
Job location: Mumbai - Andheri (Powai)
Experience Range: 6  to 10 Years

 Role & Responsibilities:


1. Ability to work independently on assigned QA activities – doesn’t need to be directed at all times
2. Own complete QA responsibilities for application/ suite of applications
3. Maintain relationship with stakeholders including dev teams, BA teams & users
4. Work with dev teams by sharing system QA metrics and work towards system/ user value
improvements
5. Mentor junior members in the team
6. Pro-actively look for opportunities to improve business value derived from application

Mandatory Desired Technologies :

1. Minimum 2 years of hands-on experience with Selenium and or other functional automation test tools.
2. Solid scripting and programming skills (with emphasis on Java, VBScript, SQL)
3. Strong troubleshooting skills, Strong analytical and problem-solving
4. Hands-on expertise to design automation framework
5. Knowledge of different manual testing methodologies and test documentation procedures including   ETL testing.
6. Ability to execute manual test cases and document actual results within the tool.
7. Expertise in Manual Systems/Unit/Integration Testing
8. Knowledge of HP ALM.
9. Ability to formalize test results into a document that communicates findings
10. Well versed with QA processes and tools. Knowledge of Financial and Banking applications will      be    an added advantage
11. Any automation certifications, experience in performance testing

If interested Kindly share your updated CV on prachi.ukey@seedinfotech.com along with below details:

Total exp:
 Relevant experience with Selenium and or other functional automation test tools:
Current CTC:
Expected CTC:
Notice period:


Regards,
 Prachi Ukey | JR. Officer-Staffing|
Intellectual Resource Center,
SEED Info tech Pvt ltd,Pune

By Default time of WAITFOR command is

By Default time of WAITFOR command in Selenium Webdriver,While working with AJAX Applications,it is required to wait our Selenium Test Scripts until loading is completes,in order to verify whether expected test element is displaying or not at that time we can use Selenium waiting commands in Test Scripts.

By Default WAITFOR Command is


By Default time of WAITFOR Command

Options are as below

1. 15 seconds
2. 20 seconds
3 25 seconds
4.30 seconds

ANSWER : 30 Seconds

Trending Posts:

Which Testing is PERFORMED First


Please provide your valuable comments on this Posts,In case you feel answer is not proper,Please provide your answers in below Comment section.Thank you for Reading.

Which Testing is performed first

Which testing is Performed First,In software Testing process it is little bit confuse that how to start Testing on AUT and in STLC which Testing is performed first.Let's discuss the same with below questions.

Which Testing is Performed First


Which Testing is performed first

In Interview room difinitely you will face this type questions,so it is very easy to answer those type of questions.

Choose the Below Options:

1. Black box testing
2. White box testing
3. Dynamic testing
4. Static testing

Above Question ANSWER is Static Testing.

What is Static Testing?

Static Testing is a type of technique by which you can verify the error or defects in software without Test Cases execution.Static testing is performed to avoid defects an early stage of development and it is easy to find sources of failures.Static testing helps to find defects that may not be found in Dynamic Testing technique.

Types of static testing techniques

There are two types of static testing techniques,those are as follows

1.Manual Examinations: Manual examinations verifies analysis of code written manually, and it is also called as REVIEWS.
2.Automated analysis using tools: Automated analysis are basically static analysis which is performed using any automation tools.

How to Select a Dropdown in Selenium WebDriver using Java

In order to select a dropdown value using Selenium WebDriver we have to create a Select an element and will not use the default WebElements provided by Selenium Webdriver.

Let's consider below drop-down example to select a value using Selenium WebDriver.




1.HTML Dropdown Code:

<select id="citySelect">
<option value="option1">Ahmedabad</option>
<option value="option2">Hyderabad</option>
<option value="option3">Mumbai</option>
<option value="option4">Pune</option>
</select>


1.1 Identify the HTML Element to Select value

Selenium WebDriver providing WebElement class to  identify the or store web element as below

WebElement CitySelection = driver.findElement(By.id("citySelect"));
Select dropdown= new Select(CitySelection);

Another method is directly you can pass in WebElement as below

Select dropdown = new Select(driver.findElement(By.id("citySelect")));


1.2 Select an Option

You can select drodown options by three ways

1.selectByVisibleText(String)
2.selectByIndex(int)
3.selectByValue(String)


2.1 selectByVisibleText:

You can select dropdown value by matching visible text as below

dropdown.selectByVisibleText("Hyderabad")


2.2 selectByIndex:

You can select the dropDown value by index attribute of an element as below

dropdown.selectByIndex(2)

index =1 means Ahmedabad
index=2 means Hyderabad


2.3 selectByValue:

You can select dropDown value by Optioon Value in above HTML code we've used multiple options 1,2,3,4 and code will be

drodown.selectByValue("option2")
dropdown.selectByValue("option1")


3.Complete Selenium Webdriver Code as follows:

WebElement CitySelection = driver.findElement(By.id("citySelect"));
Select dropdown= new Select(CitySelection);
dropdown.selectByIndex(2);
dropdown.selectByValue("option1");
dropdown.selectByVisibleText("Hyderabad");