Selenium-Table 封裝-小練習

題目:使用css定位器獲取table元素並計算1月與2月商品總計,計算錯誤則顯示正確金額是多少,當前計算金額是多少,誤差多少。

 

from selenium import webdriver
from time import sleep


#定義類
class table_css():
    #init構造函數:定義必不可少的參數
    def __init__(self, driver, tbody):
        self.driver = driver
        self.tbody = tbody

    #get_table_tr構造函數:獲取tr  td類型的數據,即獲取【衣服】【化妝品】【食物】行數據
    def get_table_tr(self,row,coloum):
        # #table > tbody > tr:nth-child(2) > td:nth-child(2)
        csspath = self.tbody + '> tr:nth-child(' + str(row) + ') > td:nth-child(' + str(coloum) + ')'
        return self.driver.find_element_by_css_selector(csspath).text

    # get_table_th構造函數:獲取tr  td類型的數據,即獲取【總計】行數據
    def get_table_th(self, row, coloum):
        # #table > tbody > tr:nth-child(5) > th:nth-child(2)
        csspath = self.tbody + ' > tr:nth-child(' + str(row) + ') > th:nth-child(' + str(coloum) + ')'
        return self.driver.find_element_by_css_selector(csspath).text


    #compare構建函數,比較計算三行的值sum和總計值total的大小
    def compare(self,sum,total):
        #輸出一月計算正確,二月計算錯誤,計算爲多少,展示爲多少,誤差爲多少;
        if sum != total:
            return  '計算錯誤,計算值爲:%d ,總計展示爲: %d ,誤差爲: %d' %(sum,total,sum-total)
        else:
            return  '計算正確'

brower = webdriver.Chrome()
#請求testtable.html頁面
brower.get( 'file:///C:/UI/testtable.html')
sleep(2)
# #table > tbody > tr:nth-child(2) > td:nth-child(2)
table = table_css(brower, '#table > tbody')
# print(table.get_table_tr(2,2))
# print(table.get_table_tr(3,3))
# #輸出table.get_cell_text(1,1)會報錯,因爲第一列和第四列爲th,打印的話需要重新定義
# print(table.get_table_th(1,1))
# brower.quit()

# ①計算並比較一月
Jansum = int(table.get_table_tr(2,2)) + int(table.get_table_tr(3,2)) + int(table.get_table_tr(4,2))
Jantotal = int(table.get_table_th(5,2))
print('一月' + table.compare(Jansum,Jantotal))
# ①計算並比較二月
Febsum = int(table.get_table_tr(2,3)) + int(table.get_table_tr(3,3)) + int(table.get_table_tr(4,3))
Febtotal = int(table.get_table_th(5,3))
print('二月' + table.compare(Febsum,Febtotal))

brower.quit()
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章