selenium+python tableデータを取得する例を説明します。

3067 ワード

方法1:

<code class="language-python">""" 
  table id   table           table     
table    ,       1    
tableId:table id   
queryContent:          
""" 
def get_table_content(tableId,queryContent): 
  arr = [] 
  arr1 = []  
  table_loc = (By.ID,tableId) 
  #          ,         ,            
  table_tr_list = driver.find_element(*table_loc).find_elements(By.TAG_NAME, "tr") 
  for tr in table_tr_list: 
    arr1 = (tr.text).split(" ") #         (         )     
    # print(tr.text) 
    # print(arr1) 
    arr.append(arr1)  #             
 
  #    table  ,          
  for i in range(len(arr)): 
    for j in range(len(arr[i])): 
      if queryContent== arr[i][j]: 
        print("%r   (%r,%r)" %(queryContent,i+1,j+1)) 
 
get_table_content("myTable","      ")</code> 
方法二:

"""
  table id   table           table    
table    ,       1   
tableId:table id  
queryContent:         
"""
def get_table_content(tableId,queryContent):
 
  #          ,         ,           
  table_tr_list = driver.find_element(By.ID, tableId).find_elements(By.TAG_NAME, "tr")
  table_list = [] #  table  
  for tr in table_tr_list:  #     tr
    #    tr     td    ,     list  
    table_td_list = tr.find_elements(By.TAG_NAME, "td")
    row_list = []
    print(table_td_list)
    for td in table_td_list:  #     td
      row_list.append(td.text)  #       ,       
    table_list.append(row_list)
 
  #     table  ,         
  for i in range(len(table_list)):
    for j in range(len(table_list[i])):
      if queryContent== table_list[i][j]:
        print("%r   (%r,%r)" %(queryContent,i+1,j+1))
 
get_table_content("myTable","      ")
方法三:

"""
  CSS    table           table    
table    ,       1   
cssSelector:table CSS     
queryContent:         
"""
def get_table_content(cssSelector,queryContent):
  locator = cssSelector + ">tbody>tr"
  table_list = []
  table_tr_list = driver.find_elements(By.CSS_SELECTOR, locator)[1:] #    
  for tr in table_tr_list:
    row_list = []
    table_td_list = tr.find_elements(By.TAG_NAME,"td")
    for td in table_td_list:
      row_list.append(td.text)
    table_list.append(row_list)
 
  for i in range(len(table_list)):
    for j in range(len(table_list[i])):
      if queryContent== table_list[i][j]:
        print("%r   (%r,%r)" %(queryContent,i+1,j+1))
 
get_table_content("#myTable","      ")
以上のselenium+pythonがtableデータを取得した例の解説は小編が皆さんに共有した内容の全部です。参考にしてもらいたいです。どうぞよろしくお願いします。