# selenium

***

**1. Basic Web Page Navigation**

```python
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.google.com")
driver.quit()
```

**2. Finding Elements by ID**

```python
driver.find_element_by_id("search-input")
```

**3. Finding Elements by Class Name**

```python
driver.find_elements_by_class_name("search-result")
```

**4. Finding Elements by Name**

```python
driver.find_element_by_name("q")
```

**5. Finding Elements by XPath**

```python
driver.find_element_by_xpath("//input[@id='search-input']")
```

**6. Finding Elements by CSS Selector**

```python
driver.find_element_by_css_selector("#search-input")
```

**7. Entering Text into an Input Field**

```python
input_field = driver.find_element_by_id("search-input")
input_field.send_keys("Selenium")
```

**8. Clicking on a Button**

```python
button = driver.find_element_by_id("search-button")
button.click()
```

**9. Getting the Page Title**

```python
title = driver.title
```

**10. Getting the Page URL**

```python
url = driver.current_url
```

**11. Getting the Page Source**

```python
source = driver.page_source
```

**12. Waiting for an Element to Be Present**

```python
from selenium.webdriver.support.ui import WebDriverWait
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, "search-input")))
```

**13. Waiting for an Element to Be Clickable**

```python
wait.until(EC.element_to_be_clickable((By.ID, "search-button")))
```

**14. Waiting for a Page to Load**

```python
wait.until(EC.title_contains("Search Results"))
```

**15. Scrolling to an Element**

```python
element = driver.find_element_by_id("footer")
driver.execute_script("arguments[0].scrollIntoView();", element)
```

**16. Taking a Screenshot**

```python
driver.save_screenshot("screenshot.png")
```

**17. Accepting an Alert**

```python
from selenium.common.exceptions import NoAlertPresentException
try:
    alert = driver.switch_to.alert
    alert.accept()
except NoAlertPresentException:
    pass
```

**18. Dismissing an Alert**

```python
try:
    alert = driver.switch_to.alert
    alert.dismiss()
except NoAlertPresentException:
    pass
```

**19. Handling Multiple Windows**

```python
window_handles = driver.window_handles
driver.switch_to.window(window_handles[1])
driver.close()
driver.switch_to.window(window_handles[0])
```

**20. Handling Frames**

```python
driver.switch_to.frame("frame-name")
driver.switch_to.default_content()
```

**21. Handling Cookies**

```python
cookies = driver.get_cookies()
driver.add_cookie({"name": "cookie-name", "value": "cookie-value"})
```

**22. Handling JavaScript**

```python
driver.execute_script("return document.title;")
```

**23. Setting User Agent**

```python
user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36"
driver.execute_cdp_cmd("Network.setUserAgentOverride", {"userAgent": user_agent})
```

**24. Disabling Images**

```python
driver.execute_cdp_cmd("Page.setWebLifecycleState", {"state": "inactive"})
```

**25. Emulating Mobile Devices**

```python
mobile_emulation = {"deviceName": "iPhone 6"}
driver.execute_cdp_cmd("Emulation.setDeviceMetricsOverride", mobile_emulation)
```

**26. Bypassing CAPTCHA Using 2CAPTCHA**

```python
import twilio

client = twilio.rest.Client(account_sid, auth_token)
message = client.messages \
                .create(
                    body="Enter the captcha code: %s" % captcha_code,
                    from_='+1234567890',
                    to='+0987654321'
                )
```

**27. Parsing HTML with Beautiful Soup**

```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(driver.page_source, "html.parser")
```

**28. Data Scraping from a Web Page**

```python
data = []
for row in soup.find_all("tr"):
    data.append([cell.text for cell in row.find_all("td")])
```

**29. Web Automation for Data Extraction**

```python
import pandas as pd
data = pd.read_html("http://www.example.com/table.html")[0]
```

**30. Web Testing for Broken Links**

```python
import requests

for link in soup.find_all("a"):
    try:
        requests.get(link["href"])
    except requests.exceptions.RequestException:
        print("Broken link found: %s" % link["href"])
```

**31. Web Testing for Performance**

```python
import timeit

def test_page_load():
    driver.get("http://www.google.com")

result = timeit.timeit("test_page_load()", number=10)
```

**32. Creating Custom Firefox Profile**

```python
from selenium.webdriver.firefox.options import FirefoxProfile

profile = FirefoxProfile()
profile.set_preference("browser.cache.disk.enable", False)
driver = webdriver.Firefox(firefox_profile=profile)
```

**33. Running Selenium Tests in Headless Mode**

```python
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=options)
```

**34. Using Selenium Grid**

```python
from selenium.webdriver.remote.webdriver import WebDriver

driver = WebDriver("http://localhost:4444/wd/hub", DesiredCapabilities.CHROME)
```

**35. Creating a Web Driver Manager**

```python
from selenium.webdriver.chrome.webdriver import WebDriver
from webdriver_manager.chrome import ChromeDriverManager

driver = WebDriver(ChromeDriverManager().install())
```

**36. Using WebDriver Wait**

```python
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

wait = WebDriverWait(driver, 10)
element = wait.until(EC.presence_of_element_located((By.ID, "element-id")))
```

**37. Finding Elements Using Different Strategies**

```python
from selenium.webdriver.common.by import By

driver.find_element(By.ID, "element-id")
driver.find_element(By.CLASS_NAME, "element-class")
driver.find_element(By.TAG_NAME, "element-tag")
```

**38. Handling Pop-ups and Alerts**

```python
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

wait = WebDriverWait(driver, 10)
alert = wait.until(EC.alert_is_present())
alert.accept()
```

**39. Capturing Screenshots and Videos**

```python
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions import Screenshot

driver.save_screenshot("screenshot.png")
driver.get_screenshot_as_file("screenshot.png")

actions = ActionChains(driver)
actions.screenshot().perform()
```

**40. Customizing Test Assertions**

```python
import unittest

class MyTest(unittest.TestCase):

    def test_something(self):
        self.assertEqual(driver.title, "Expected Title")
        self.assertNotEqual(driver.title, "Unexpected Title")
```

**41. Using Page Objects**

```python
class LoginPage:

    def __init__(self, driver):
        self.driver = driver
        self.username_field = driver.find_element(By.ID, "username")
        self.password_field = driver.find_element(By.ID, "password")

    def login(self, username, password):
        self.username_field.send_keys(username)
        self.password_field.send_keys(password)
        self.password_field.submit()
```

**42. Using Test Suites and Test Runners**

```python
import unittest

class MyTestSuite(unittest.TestSuite):

    def addTest(self, test_case):
        if test_case.id().startswith("test_something"):
            super().addTest(test_case)

unittest.TextTestRunner().run(MyTestSuite())
```

**43. Handling Dynamic Content**

```python
import time

while True:
    try:
        element = driver.find_element(By.ID, "dynamic-element")
        break
    except NoSuchElementException:
        time.sleep(1)
```

**44. Using JavaScript Executor**

```python
driver.execute_script("arguments[0].scrollIntoView();", element)
driver.execute_script("return document.title;")
```

**45. Working with Frames and Windows**

```python
driver.switch_to.frame("frame-name")
driver.switch_to.default_content()

handles = driver.window_handles
driver.switch_to.window(handles[1])
```

**46. Using Expected Conditions**

```python
import selenium.webdriver.support.expected_conditions as EC
import selenium.webdriver.support.ui as WebDriverWait

element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "element-id"))
)
```

**47. Handling WebSockets**
