HTML таблица в CSV скребок - PullRequest
0 голосов
/ 02 января 2019

Я пытаюсь почистить таблицу на следующем веб-сайте, но не смог этого сделать:

https://www.moneycontrol.com/financials/relianceindustries/ratiosVI/RI?classic=true#RI

import csv

from bs4 import BeautifulSoup

from urllib.request import urlopen

soup = BeautifulSoup(urlopen('https://www.moneycontrol.com/financials/relianceindustries/ratiosVI/RI?classic=true#RI'))

table = soup.find('table', attrs={ "class" : "table-horizontal-line"})

headers = [header.text for header in table.find_all('th')]

rows = []

for row in table.find_all('tr'):
    rows.append([val.text.encode('utf8') for val in row.find_all('td')])

with open('output_file.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(headers)
    writer.writerows(row for row in rows if row)

1 Ответ

0 голосов
/ 02 января 2019

Вы можете использовать панды для этого.Вверху есть пара строк, которые вы можете удалить и заменить некоторые другие NaN пустыми строками для очистки.

import pandas as pd
result = pd.read_html('https://www.moneycontrol.com/financials/relianceindustries/ratiosVI/RI?classic=true#RI')
df = result[3].dropna(how='all').fillna('')
df.to_csv(r'C:\Users\User\Desktop\Data.csv', sep=',', encoding='utf-8',index = False )
...