Convertir des données en DataFrame en python

Dec 08 2020

Avec l'aide de @JaSON, voici un code qui me permet d'obtenir les données du tableau à partir du html local et le code utilise du sélénium

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)

Comment ces lignes peuvent-elles être converties en table valide que je peux exporter vers un fichier csv? Voici le lien HTML localhttps://pastebin.com/raw/hEq8K75C

** @Paul Brennan: Après avoir essayé de modifier le compteur, counter-1j'ai eu 17 lignes pour ignorer temporairement l'erreur de la ligne 18, j'ai obtenu le nom de fichier.txt et voici un instantané de la sortie

Réponses

1 PaulBrennan Dec 08 2020 at 19:56

J'ai modifié votre code pour faire une sortie simple. Ce n'est pas très pythonique car il n'utilise pas la création vectorisée du Dataframe, mais voici comment cela fonctionne. Commencez par configurer les pandas, puis configurez un dataframe (mais nous ne connaissons pas encore les colonnes) puis configurez les colonnes lors du premier passage (cela posera des problèmes s'il y a des longueurs de colonne variables.

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

Comment cela pourrait être amélioré est de mettre les éléments dans une ligne dans un dictionnaire et de les mettre dans la trame de données. mais j'écris ceci sur mon téléphone donc je ne peux pas le tester.

YasserKhalil Dec 11 2020 at 11:32

Avec la grande aide de @Paul Brennan, je pourrais modifier le code afin d'obtenir le résultat final souhaité

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]]]

Le code fonctionne bien maintenant mais il est trop lent. Y a-t-il un moyen de le rendre plus rapide?