Giter VIP home page Giter VIP logo

selenium's Introduction

test

selenium's People

Contributors

kif1205 avatar

selenium's Issues

XPATH - Contains

The outerHTML Format

<div _ngcontent-c8="" class="accordion-group">
  <div _ngcontent-c8="" class="accordion-heading accordion-heading-open">
    
    
    <div _ngcontent-c8="" class="accordion-title d-flex justify-content-between">
      <div _ngcontent-c8="">bmc</div>
      <!---->
      <div _ngcontent-c8="" class="accordion-toggle"></div>
      
        
      
    </div>

  </div>
  <div _ngcontent-c8="" class="panel-collapse">
    <div _ngcontent-c8="" class="panel-body">
      
          <div class="card">
            <div class="card-block">
            <app-firmware-inventory><form class="form ng-valid ng-dirty ng-touched" novalidate="">

  <div>
  <div class="form-group row">
    <label class="control-label col-sm-4">Name</label>
    <div class="col-md-4">
      <div>bmc Firmware</div>
    </div>
  </div>

    <div class="form-group row">
      <label class="control-label col-sm-4">Status</label>
      <div class="col-md-4">
        <div>Enabled</div>
      </div>
    </div>

    <div class="form-group row">
      <label class="control-label col-sm-4">Version</label>
      <div class="col-md-4">
        <div>v3.0-2019-r7-dev-20190802150352</div>
      </div>
    </div>

    <!----><div class="form-group row pr-4 pl-4">
      <fieldset class="scheduler-border">
        <legend class="scheduler-border">Update
          <div class="radio-item">
            <input type="radio" id="rdoUploadType1bmc" class="ng-untouched ng-pristine" disabled="">
            <label for="rdoUploadType1bmc">TFTP</label>
          </div>
          <div class="radio-item">
            <input disabled="" type="radio" id="rdoUploadType2bmc" class="ng-untouched ng-pristine">
            <label for="rdoUploadType2bmc">Image Upload</label>
          </div>
        </legend>
        <!----><div class="form-group row">
            <label class="control-label col-sm-4">TFTP Path</label>
            <div class="col-md-6">
              <!---->
                <div>
                  <input name="txtTFTPPath" required="" size="25" type="text" class="ng-valid ng-dirty ng-touched">
                </div>
                <div class="pt-2">
                  <button class="btn btn-vertiv" type="button">
                    Start Update
                  </button>
                </div>
              
              <!---->
            </div>
        </div>
        <!---->
      </fieldset>
    </div>

  </div>
</form>
</app-firmware-inventory>
            </div>
          </div>
        
    </div>
  </div>
</div>

Selenium - Login with a pop up window

This window is not alert window

image

Sample code :

from selenium import webdriver
import time
import win32com.client

# Setup
# pip install pypiwin32
# pip install selenium

# Reference :
# Login Window : https://stackoverflow.com/questions/40671662/how-to-handle-windows-authentication-popup-in-selenium-using-pythonplus-java

driver_location = "C:\web_driver\chromedriver.exe"
DUT_location = "http://192.168.1.1"
username = "admin"
password = "22Ejdkhc"

driver = webdriver.Chrome(driver_location)
#driver.maximize_window()
driver.get(DUT_location)

shell = win32com.client.Dispatch("WScript.Shell")   
shell.Sendkeys(username)  
time.sleep(2)
shell.Sendkeys("{TAB}")
time.sleep(2)
shell.Sendkeys(password) 
time.sleep(2)
shell.Sendkeys("{ENTER}")
time.sleep(2)

# Logout and close the browser
#driver.quit()

Selenium - scroll_into_view

# #X_TABLE_BASE = "//app-root//app-logs//app-eventlog//data-table"
# com_drop = DropdownButtonComponent(WebData.web_conn._ctx)
# err_drop, dom_drop = com_drop.locate_self("XPath", table_xpath)
# com_drop._locator.scroll_into_view(dom_drop)

Selenium wait - Explicit Waits

Official page : https://selenium-python.readthedocs.io/waits.html

Sample code :

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()
  • Expected Conditions

There are some common conditions that are frequently of use when automating web browsers. Listed below are the names of each. Selenium Python binding provides some convenience methods so you don’t have to code an expected_condition class yourself or create your own utility package for them.

title_is
title_contains
presence_of_element_located
visibility_of_element_located
visibility_of
presence_of_all_elements_located
text_to_be_present_in_element
text_to_be_present_in_element_value
frame_to_be_available_and_switch_to_it
invisibility_of_element_located
element_to_be_clickable
staleness_of
element_to_be_selected
element_located_to_be_selected
element_selection_state_to_be
element_located_selection_state_to_be
alert_is_present

Selenium - Execute JavaScript function

Reference : https://dzone.com/articles/perform-actions-using-javascript-in-python-seleniu

Element :

<area shape="rect" coords="111,84,155,655" alt="Cell ID: 2.
Module: 1
Voltage: 30.00 V.
High Threshold: 0.00 V.
Low Threshold: 0.00 V.
High Delta: -30.00 V.
Low Delta: 30.00 V.
Memos: 0
Baseline (US): 
Cell Balancing: False" title="Cell ID: 2.
Module: 1
Voltage: 30.00 V.
High Threshold: 0.00 V.
Low Threshold: 0.00 V.
High Delta: -30.00 V.
Low Delta: 30.00 V.
Memos: 0
Baseline (US): 
Cell Balancing: False" href="javascript:ChartItemClientClick('Cell ID: 2.
Module: 1
Voltage: 30.00 V.
High Threshold: 0.00 V.
Low Threshold: 0.00 V.
High Delta: -30.00 V.
Low Delta: 30.00 V.
Memos: 0
Baseline (US): 
Cell Balancing: False', 'imctl00_MainContent_ucStringView_ucStringViewDetails_pnlVoltageChartsWrapper_i0_i0_radchartVoltage-0-094324da-79da-42d9-9915-6956ae4dbb4e');">

=> This element can't be clicked by Selenium function, and need to be executed with Javascript as below

driver = webdriver.Chrome("chromedriver.exe")
inputElement = driver.find_element_by_xpath(xpath)
driver.execute_script("arguments[0].click();", inputElement)

Selenium - Get the page loading time

Reference : https://www.edureka.co/community/52561/how-measure-page-load-time-of-website-using-selenium-python

from selenium import webdriver

hyperlink = "http://www.baidu.com"
driver = webdriver.Chrome("chromedriver.exe")
driver.get(hyperlink)
 
navigationStart = driver.execute_script("return window.performance.timing.navigationStart")
responseStart = driver.execute_script("return window.performance.timing.responseStart")
domComplete = driver.execute_script("return window.performance.timing.domComplete")

backendPerformance_calc = responseStart - navigationStart
frontendPerformance_calc = domComplete - responseStart
 
print("Back End: %s" % backendPerformance_calc)
print("Front End: %s" % frontendPerformance_calc)
 
driver.quit()

How to remove the detect string in chromedriver

Summary :
Some websites will detect the simulator string , the related should be removed to avoid the detection


How to do :
vim /path/to/chromedriver
After running the line above, you'll probably see a bunch of gibberish. Do the following:

Replace all instances of cdc_ with dog_ by typing :%s/cdc_/dog_/g.
dog_ is just an example. You can choose anything as long as it has the same amount of characters as the search string (e.g., cdc_), otherwise the chromedriver will fail.
To save the changes and quit, type :wq! and press return.
If you need to quit without saving changes, type :q! and press return.


Reference : https://stackoverflow.com/questions/33225947/can-a-website-detect-when-you-are-using-selenium-with-chromedriver

Selenium - How to start on Firefox WebDriver

coding=utf-8

from selenium import webdriver
driver = webdriver.Firefox(executable_path="C:\Python34\selenium\webdriver\geckodriver.exe")
driver.get("http://www.baidu.com")

driver.find_element_by_id("kw").send_keys("Selenium2")
driver.find_element_by_id("su").click()
driver.quit()

XPATH - 解析絕對路徑

XPATH : /html/body/app-root/nav/app-header/div/div/div[3]/div/div[1]

=> app-header : <app-header>...</app-header>
=> div : <div> without </div>
=> div[3] : the third place of  the below examples :  
                 <div></div> : 1
                 <div></div> : 2
                 <div></div> : 3
                 <div></div> : 4
=> div : <div></div> => Thus this div can't be ignored
=> div[1] : the first place of the below examples : 
                 <div></div> : 1
                 <div></div> : 2

outerHTML5 format

<nav _ngcontent-c0="" class="navbar navbar-inverse navbar-fixed-top bg-vertiv-header">
  <app-header _ngcontent-c0="" _nghost-c1="">
<div _ngcontent-c1="" class="navbar-header">
<div _ngcontent-c1="" class="d-flex flex-row justify-content-between row-h1 navbar-header w-100">
  <div _ngcontent-c1="" clsas="p-1 item-h1">
    <a _ngcontent-c1="" class="navbar-brand">
      <img _ngcontent-c1="" alt="Vertiv LOGO" class="img-fluid img-logo" src="assets/images/ver_logo_tm_hrz_rgb_rev.png">
    </a>
  </div>
  <div _ngcontent-c1="" class="pt-3 item-h1">
    <img _ngcontent-c1="" alt="Corona LOGO" class="img-responsive corona-logo" src="assets/images/corona-logo.png">
  </div>
  <div _ngcontent-c1="" class="pr-4 item-h1">
    <div _ngcontent-c1="" class="d-flex flex-column justify-content-center h-100" style="text-align: right;">
      <!----><div _ngcontent-c1="" class="navbar-user-info text-nowrap d-none d-md-block">admin </div>
      <!----><div _ngcontent-c1="" class="navbar-user-info text-nowrap d-none d-md-block">10.162.246.133 </div>
    </div>
  </div>
  <div _ngcontent-c1="" class="pr-4 item-h1">
    <div _ngcontent-c1="" class="d-flex flex-column justify-content-center h-100" style="text-align: right;">
      <div _ngcontent-c1="" class="versionInfo text-nowrap">Version 1.1.9</div>
      <!----><div _ngcontent-c1="" class="navbar-exit">
        <a _ngcontent-c1="">
          <i _ngcontent-c1="" class="fa fa-sign-out cursor-pointer"></i>
          Logout
        </a>
      </div>
    </div>
  </div>

  </div>
</div>


</app-header>
</nav>

Headless

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from bs4 import BeautifulSoup
import json

options = Options()
options.add_argument("--headless")
driver_path = 'chromedriver.exe'  # webdriver執行檔路徑。這最好寫在設置檔中,這裡為方便說明才直接寫在代碼中。
driver = webdriver.Chrome(executable_path=driver_path, chrome_options=options)
print("########## driver : " , driver)
driver.get('http://www.google.com/')  # 這個URL是虛構的,原本的URL必須等待數秒鐘之後才會出現所要的JSON資料
WebDriverWait(driver, 18, 6).until_not(lambda x: x.find_element_by_id('x_id').is_displayed())  # 這個x_id也是虛構的
soup = BeautifulSoup(driver.page_source, 'html.parser')
print("########## soup : " , soup)
driver.quit()
content = soup.body.get_text()  # 取得其中的JSON文字。可與下一行寫成一行,這裡為方便說明,分成兩行。
print("########## content : " , content)
data = json.loads(content)
print("########## data : " , data)

Selenium - 幾種定位

coding=utf-8

from selenium import webdriver
driver = webdriver.Firefox(executable_path="C:\Python34\selenium\webdriver\geckodriver.exe")
driver.get("http://www.baidu.com")

Find by "id"

#driver.find_element_by_id("kw").send_keys("Selenium2")
#driver.find_element_by_id("su").click()

Find by "class name"

#driver.find_element_by_class_name("s_ipt").send_keys("Selenium2")
#driver.find_element_by_class_name("s_btn").click() #檢測元素找到是 "bg s_btn" , 不過s_btn才不會報錯 , 有partial find?

Find by "name" and "link_text"

#driver.find_element_by_name("wd").send_keys("Selenium2") # Find by "name"
#driver.find_element_by_link_text("百度一下").click() # Find by "link_text" => 報錯

Find by "xpath"

driver.find_element_by_xpath('//[@id="kw"]').send_keys("Selenium2")
driver.find_element_by_xpath('//
[@id="su"]').click()

#driver.quit() # 關掉Firefox並離開

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.