PythonでデータをDataFrameに変換する

Dec 08 2020

@JaSONの助けを借りて、ローカルhtmlからテーブル内のデータを取得できるようにするコードがあります。コードはセレンを使用します

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)

これらの行を、csvファイルにエクスポートできる有効なテーブルに変換するにはどうすればよいですか?これがローカルHTMLリンクですhttps://pastebin.com/raw/hEq8K75C

** @Paul Brennan:カウンターを編集してcounter-1、行18のエラーを一時的にスキップするために17行を取得しようとした後、filename.txtと出力のスナップショットを取得しました。

回答

1 PaulBrennan Dec 08 2020 at 19:56

簡単な出力を行うようにコードを変更しました。これは、データフレームのベクトル化された作成を使用しないため、あまりPython的ではありませんが、その仕組みは次のとおりです。最初にパンダを設定し、次にデータフレームを設定し(ただし、列はまだわかりません)、最初のパスで列を設定します(これにより、列の長さが可変の場合に問題が発生します。次に、データフレームに値を入力します。

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

これを改善する方法は、アイテムを一列に並べて辞書に入れ、それらをデータフレームに入れることです。しかし、私は自分の電話でこれを書いているので、それをテストすることはできません。

YasserKhalil Dec 11 2020 at 11:32

@Paul Brennanの多大な助けを借りて、最終的に望ましい出力が得られるようにコードを変更することができました。

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

コードは今はうまく機能していますが、遅すぎます。それを速くする方法はありますか?