Chuyển đổi dữ liệu sang DataFrame trong python

Dec 08 2020

Với sự trợ giúp của @JaSON, đây là mã cho phép tôi lấy dữ liệu trong bảng từ html cục bộ và mã sử dụng selen

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)

Làm cách nào để các hàng này được chuyển đổi thành bảng hợp lệ mà tôi có thể xuất sang tệp csv? Đây là liên kết HTML cục bộhttps://pastebin.com/raw/hEq8K75C

** @Paul Brennan: Sau khi cố gắng chỉnh sửa bộ đếm thành counter-117 hàng để tạm thời bỏ qua lỗi của hàng 18, tôi nhận được filename.txt và đây là ảnh chụp nhanh của kết quả

Trả lời

1 PaulBrennan Dec 08 2020 at 19:56

Tôi đã sửa đổi mã của bạn để thực hiện một đầu ra đơn giản. Điều này không quá khó hiểu vì nó không sử dụng việc tạo vectơ hóa của Dataframe, nhưng đây là cách nó hoạt động. Đầu tiên thiết lập gấu trúc, thứ hai thiết lập khung dữ liệu (nhưng chúng tôi chưa biết các cột) sau đó thiết lập các cột trên đường truyền đầu tiên (điều này sẽ gây ra vấn đề nếu có độ dài cột thay đổi Sau đó nhập các giá trị vào khung dữ liệu

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

Cách làm này tốt hơn là đặt các mục trong một hàng vào từ điển và đưa chúng vào khung dữ liệu. nhưng tôi đang viết điều này trên điện thoại của mình nên tôi không thể kiểm tra điều đó.

YasserKhalil Dec 11 2020 at 11:32

Với sự trợ giúp đắc lực của @Paul Brennan, tôi có thể sửa đổi mã để có được đầu ra mong muốn cuối cùng

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

Hiện tại mã hoạt động tốt nhưng quá chậm. Có cách nào để làm cho nó nhanh hơn?