# Articles about python

# Tips

Random generated strings with letters and digits:

import random, string
_code_lib = string.ascii_letters + string.digits + string.ascii_letters.upper()

def getRandomCode( bit = 6 ):
    """generate random string which contains of letters and digits
    """
    return ''.join( random.SystemRandom().choices( _code_lib, k = bit ) )

1
2
3
4
5
6
7
8

# Automated Browser Actions

[Selenium] may be the eaysest way to use, which contains serveral APIs which is simple enghou. We can find a HTML DOM Element by using id, name, attribute and even xpath. That is similar to JS DOM manipulation, is it?

For example, we have the following HTML code from one site:

<!DOC>
<html>
  <body>
     <form id='formA' class='formA' type='form'>
        <input id='inputA' type='text'> /
        <input id='inputB' name='inputB' />
        <input id='inputC' type='password' />
     </form>
  </body>
</html>
1
2
3
4
5
6
7
8
9
10

Then we can get the first Input Element by selenium:

# introduce selenium
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
1
2
3
4
5
6
7

Then we can create the driver instance and implement the automated actions:

# get the browser driver instance
chrome = WebDriver.Chrome()

# either find_element
inputA = chrome.find_element(By.ID, "inputA")
# or find_element_by_id
inputA = chrome.find_element_by_id("inputA")

# or find_element_by_name
inputB = chrome.find_element_by_name('inputB')

# or find_element_by_xpath and attribute
inputC = chrome.find_element_by_xpath('//input[@type="password"]')
1
2
3
4
5
6
7
8
9
10
11
12
13

Note, if you try to find an element that not exists or some elements not loaded due to the network problem, your program may encountered the problem said NoSuchElementException, so you have to encapsulate the code with try-catch block which may protect the program from exiting unnormally.

View Selenium-Python to learn more about selenium and w3schools to learn more about xpath.

Last Updated: 3/17/2020, 2:23:20 AM