собирать TR из таблицы html в csv, используя python и beautifulsoup - PullRequest
0 голосов
/ 05 августа 2020

так что я пробовал много способов; Я хочу собрать таблицы отключений с сайта Hydro. затем сохраните его в csv как таблицу.

я проверил, что обычно tr имеет 3 td (кроме заголовка, получал ошибку, поэтому я поставил if для подсчета tr tds, если он равен 3, но каким-то образом с beautifulsoup it обнаруживает только 1 td. после того, как нужно поместить его в csv: a, b, c d, e, f ...

код:

import requests
import numpy as np
import pandas as pd
import csv
from bs4 import BeautifulSoup

URL = 'http://poweroutages.hydroquebec.com/poweroutages/service-interruption-report/#bis'
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')

table = soup.findAll('table')[0].findAll('tr')
print(table)
rates = {}
for tr in soup('tr'):

    if len(tr('td')) == 3:
        region_td, interruptions_td, cx_td = tr('td')
        print('hello')
        region = print(region_td)('i')[0]['title']
        interruptions = float(interruptions_td.text)
        cx = print(cx_td)('i')[0]['title']
        rates[region] = [interruptions, cx]

вывод или результат:

import requests
import numpy as np
import pandas as pd
import csv
from bs4 import BeautifulSoup

URL = 'http://poweroutages.hydroquebec.com/poweroutages/service-interruption-report/#bis'
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')

table = soup.findAll('table')[0].findAll('tr')
print(table)
rates = {}
for tr in soup('tr'):

    if len(tr('td')) == 3:
        region_td, interruptions_td, cx_td = tr('td')
        print('hello')
        region = print(region_td)('i')[0]['title']
        interruptions = float(interruptions_td.text)
        cx = print(cx_td)('i')[0]['title']
        rates[region] = [interruptions, cx]

другой способ, который я пробовал, работал, но смог поместить все в один массив, а в нижнем колонтитуле было 2 tds вместо 3. код 2:

import requests
import numpy as np

import pandas as pd
from bs4 import BeautifulSoup

URL = 'http://poweroutages.hydroquebec.com/poweroutages/service-interruption-report/#bis'
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')

n_interruptions = [i.text for i in soup.findAll('td')]

outageqc = pd.DataFrame({
    "n_interruptions": n_interruptions

})

outageqc.set_index('n_interruptions', inplace=True)

print(outageqc)
x = len(outageqc) / 3

вывод:

Индекс: [Abitibi-Témiscamingue, 0, 0 клиентов из 81377, Bas-Saint-Laurent, 0, 0 клиентов из 123 929, Capitale-Nationale, 6, 2 589 клиентов из 424080, Центр-дю-Квеб c, 28, 3 547 клиентов из 140 391, Шодьер-Аппалаш, 14, 3 384 клиента из 244 321, Кот-Нор, 0, 0 клиентов из 48 101, Эстр ie, 44, 1 684 клиента из 90 947, Гаспес ie - Иль-де-ла-Мадлен, 0, 0 клиент из 57 355, Ланодьер, 9, 240 клиентов из 255 267, Лаурентид, 3 , 5 1 клиент из 350 118, Лаваль, 5, 939 клиентов из 193 619, Маури cie, 19, 4251 клиент из 165 191, Монреаль, 4, 1067 клиентов из 1 058 896, Монтерег ie, 61, 9 380 клиентов из 786 889, Нор-дю-Квеб c, 0, 0 клиентов из 22 127, Outaouais, 6, 71 клиент из 219 701, Сагеней - Ла c - Сен-Жан, 0, 0 клиентов из 130 952, 199, 27 203 клиентов из 4 393 261]

у этого первого столбца не указан нижний колонтитул.

1 Ответ

0 голосов
/ 05 августа 2020

спасибо Sushanth за подсказку ,,, исправлено

from bs4 import BeautifulSoup

import io
import requests
import pandas as pd
from zipfile import ZipFile

df = pd.read_html('http://poweroutages.hydroquebec.com/poweroutages/service-interruption-report/#bis')

for i, table in enumerate(df):
    table.to_csv('test.csv', ',')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...