# coding:utf-8
"""
页面 table处理
""" from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException class WebTable(object): def __init__(self, webElement):
self.webTable = webElement #得到表格中的行数
def getRowCount(self):
rowConunts = self.webTable.find_elements(By.TAG_NAME, 'tr')
return len(rowConunts) #得到指定行的列数
def getColCount(self, rowIdx):
try:
rowCounts = self.webTable.find_elements(By.TAG_NAME, 'tr') if len(rowCounts) < rowIdx:
raise "当前行数大于表格行数" #取得当前的 tr
rowNum = rowCounts[rowIdx] #计算当前行的 td 数
colCounts = rowNum.find_elements(By.TAG_NAME, 'td')
return len(colCounts)
except NoSuchElementException as e:
raise NoSuchElementException("Failed to get the cell") #得到指定单元格内容, 传入指定的行数、列数作为参数
def getCellText(self, rowIdx, colIdx):
try:
rowCounts = self.webTable.find_elements(By.TAG_NAME, 'tr') if len(rowCounts) < rowIdx:
raise "当前行数大于表格行数" #得到对应的行数
currentRow = rowCounts[rowIdx]
#获取行中所有的td
td = currentRow.find_elements(By.TAG_NAME, 'td') if len(td) < colIdx:
raise "当前列数大于表格列数" #取得对应的单元格
cell = td[colIdx]
return cell.text
except NoSuchElementException as e:
raise NoSuchElementException("Failed to get the cell") if __name__ == '__main__':
driver = webdriver.Firefox()
driver.get('http://www.w3school.com.cn/tags/tag_table.asp')
temp_webTable = WebTable(driver.find_element(By.TAG_NAME, 'table'))
print temp_webTable.getRowCount()
print temp_webTable.getColCount(3)
print temp_webTable.getCellText(3, 2) #行和列的索引从0开始
05-11 07:47