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 행을 얻었습니다. 파일 이름 .txt를 얻었고 여기에 출력 스냅 샷이 있습니다.

답변
1 PaulBrennan Dec 08 2020 at 19:56
간단한 출력을 수행하도록 코드를 수정했습니다. 이것은 Dataframe의 벡터화 된 생성을 사용하지 않기 때문에 매우 비단뱀 적이지는 않지만 작동 방식은 다음과 같습니다. 먼저 Pandas를 설정하고 두 번째 데이터 프레임을 설정 한 다음 (아직 열을 알지 못함) 첫 번째 패스에서 열을 설정합니다 (가변 열 길이가있는 경우 문제가 발생합니다. 그런 다음 데이터 프레임에 값을 입력합니다.
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
이것이 더 나아질 수있는 방법은 항목을 행에있는 사전에 넣고 datframe에 넣는 것입니다. 하지만 저는 이것을 제 휴대폰에 쓰고있어서 테스트 할 수 없습니다.
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]]]
코드는 이제 잘 작동하지만 너무 느립니다. 더 빨리 만들 수있는 방법이 있습니까?