week 10

Week 10: Browser Automation & API Testing - 40 Python Snippets

This week covers Selenium for browser automation, interacting with web elements, Postman for API testing, and writing pytest-based API tests. Below are 40 Python snippets categorized into 4 topics (10 per topic).


1️⃣ Selenium for Browser Automation (10 Snippets)

1. Install Selenium & WebDriver

pip install selenium

2. Open a Browser & Navigate to a Page

from selenium import webdriver

driver = webdriver.Chrome()  # Make sure ChromeDriver is installed
driver.get("https://www.google.com")
print(driver.title)
driver.quit()

3. Taking a Screenshot of a Web Page

driver.get("https://www.google.com")
driver.save_screenshot("screenshot.png")
driver.quit()

4. Getting Page Source

5. Navigating Back and Forward

6. Setting Browser Window Size

7. Running Headless Browser

8. Handling Browser Alerts

9. Waiting for an Element to Load (Explicit Wait)

10. Closing the Browser


2️⃣ Interacting with Web Elements (10 Snippets)

11. Finding an Element by ID & Entering Text

12. Clicking a Button

13. Finding an Element by Name

14. Finding an Element by XPath

15. Finding an Element by CSS Selector

16. Selecting from a Dropdown Menu

17. Checking If an Element is Displayed

18. Getting Text from an Element

19. Scrolling a Web Page

20. Handling File Uploads


3️⃣ Postman for API Testing (10 Snippets)

21. Install Postman

22. Making a GET Request in Postman

  • Open Postman

  • Select GET method

  • Enter URL: https://jsonplaceholder.typicode.com/posts/1

  • Click Send

23. Making a POST Request in Postman

  • Select POST method

  • Enter URL: https://jsonplaceholder.typicode.com/posts

  • Go to BodyrawJSON and enter:

  • Click Send

24. Making a PUT Request in Postman

  • Select PUT method

  • URL: https://jsonplaceholder.typicode.com/posts/1

  • Body:

  • Click Send

25. Making a DELETE Request in Postman

  • Select DELETE method

  • URL: https://jsonplaceholder.typicode.com/posts/1

  • Click Send

26. Setting Headers in Postman

  • Go to Headers

  • Add:

    • Content-Type: application/json

    • Authorization: Bearer <token>

27. Handling Authentication in Postman

  • Go to Authorization tab

  • Select Bearer Token

  • Enter token value

28. Running a Collection in Postman

  • Click Runner

  • Select Collection

  • Click Run

29. Setting Environment Variables in Postman

  • Go to Environments

  • Add variable {{base_url}} = https://api.example.com

30. Writing a Test Script in Postman

  • Go to Tests tab

  • Add:

  • Click Send


4️⃣ Writing Pytest-Based API Tests (10 Snippets)

31. Install pytest & requests

32. Writing a Simple GET API Test

33. Running Tests with pytest

34. Writing a POST API Test

35. Testing Response JSON Format

36. Testing a DELETE API

37. Using Fixtures for Setup & Teardown

38. Parameterized API Tests

39. Testing Response Time

40. Running Tests & Generating Reports


Last updated