Converta dados em DataFrame em python

Dec 08 2020

Com a ajuda de @JaSON, aqui está um código que me permite obter os dados da tabela do html local e o código usa selênio

from selenium import webdriver

driver = webdriver.Chrome("C:/chromedriver.exe")
driver.get('file:///C:/Users/Future/Desktop/local.html')
counter = len(driver.find_elements_by_id("Section3"))
xpath = "//div[@id='Section3']/following-sibling::div[count(preceding-sibling::div[@id='Section3'])={0} and count(following-sibling::div[@id='Section3'])={1}]"
print(counter)

for i in range(counter):
    print('\nRow #{} \n'.format(i + 1))
    _xpath = xpath.format(i + 1, counter - (i + 1))
    cells = driver.find_elements_by_xpath(_xpath)
    for cell in cells:
         value = cell.find_element_by_xpath(".//td").text
         print(value)

Como essas linhas podem ser convertidas em uma tabela válida que posso exportar para um arquivo csv? Aqui está o link HTML localhttps://pastebin.com/raw/hEq8K75C

** @Paul Brennan: Depois de tentar editar o contador para counter-1obter 17 linhas para pular o erro da linha 18 temporariamente, obtive o arquivo.txt e aqui está um instantâneo da saída

Respostas

1 PaulBrennan Dec 08 2020 at 19:56

Eu modifiquei seu código para fazer uma saída simples. Isso não é muito pythônico, pois não usa a criação vetorizada do Dataframe, mas aqui está como funciona. Primeiro configure o pandas, depois configure um dataframe (mas não sabemos as colunas ainda) e então configure as colunas na primeira passagem (isto causará problemas se houver comprimentos de coluna variáveis ​​Então insira os valores no dataframe

import pandas as pd
from selenium import webdriver

driver = webdriver.Chrome("C:/chromedriver.exe")
driver.get('file:///C:/Users/Future/Desktop/local.html')
counter = len(driver.find_elements_by_id("Section3"))
xpath = "//div[@id='Section3']/following-sibling::div[count(preceding-sibling::div[@id='Section3'])={0} and count(following-sibling::div[@id='Section3'])={1}]"
print(counter)

df = pd.Dataframe()

for i in range(counter):
    print('\nRow #{} \n'.format(i + 1))
    _xpath = xpath.format(i + 1, counter - (i + 1))
    cells = driver.find_elements_by_xpath(_xpath)
    if i == 0:
        df = pd.DataFrame(columns=cells) # fill the dataframe with the column names
    for cell in cells:
        value = cell.find_element_by_xpath(".//td").text
        #print(value)
        if not value:  # check the string is not empty
            # always puting the value in the first item
            df.at[i, 0] = value # put the value in the frame

df.to_csv('filename.txt') # output the dataframe to a file

A maneira como isso poderia ser melhorado é colocar os itens em uma linha em um dicionário e colocá-los no datframe. mas estou escrevendo isso no meu telefone, então não posso testar isso.

YasserKhalil Dec 11 2020 at 11:32

Com a grande ajuda de @Paul Brennan, pude modificar o código de forma a obter o resultado final desejado

import pandas as pd
from selenium import webdriver

driver = webdriver.Chrome("C:/chromedriver.exe")
driver.get('file:///C:/Users/Future/Desktop/local.html')
counter = len(driver.find_elements_by_id("Section3"))
xpath = "//div[@id='Section3']/following-sibling::div[count(preceding-sibling::div[@id='Section3'])={0} and count(following-sibling::div[@id='Section3'])={1}]"
finallist = []

for i in range(counter):
    #print('\nRow #{} \n'.format(i + 1))
    rowlist=[]
    _xpath = xpath.format(i + 1, counter - (i + 1))
    cells = driver.find_elements_by_xpath(_xpath)
    #if i == 0:
        #df = pd.DataFrame(columns=cells) # fill the dataframe with the column names
    for cell in cells:
        try:
            value = cell.find_element_by_xpath(".//td").text
            rowlist.append(value)
        except:
            break
    finallist.append(rowlist)
    
df = pd.DataFrame(finallist)
df[df.columns[[2, 0, 1, 7, 9, 8, 3, 5, 6, 4]]]

O código funciona bem agora, mas é muito lento. Existe uma maneira de torná-lo mais rápido?