Очистка таблицы HTML в файле CSV с использованием Python в определенном формате - PullRequest
0 голосов
/ 27 мая 2018

Я хочу извлечь содержимое таблицы HTML из ссылки в определенном формате.

HTML-код на веб-странице:

<table>
<thead>
<tr>
<th>name</th>
<th>brand</th>
<th>description</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://abcd.com"><span style="color: #000; min-width: 160px;">abcd</span></a></td>
<td><a href="http://abcd.com" target="_blank"><span style="color: #000;">abcd123</span></a></td>
<td><a href="http://abcd.com" target="_blank"><span style="color: #000;">abcd 123 (1g)</span></a><br/></td>
</tr>
<tr>
<td><a href="http://efgh.com" target="_blank"><span style="color: #000; min-width: 160px;">efgh</span></a></td>
<td><a href="http://efgh.com" target="_blank"><span style="color: #000;">efgh456</span></a></td>
<td><a href="http://efgh.com" target="_blank"><span style="color: #000;">efgh 456 (2g)</span></a><br/></td>
</tr>
<tr>
<td><a href="http://ijkl.com" target="_blank"><span style="color: #000; min-width: 160px;">ijkl</span></a></td>
<td><a href="http://ijkl.com" target="_blank"><span style="color: #000;">ijkl789</span></a></td>
<td><a href="http://ijkl.com" target="_blank"><span style="color: #000;">ijkl 789 (3g)</span></a><br/></td>
</tr>
</tbody>
</table>

ОбязательноВыходной формат в CSV-файле, как показано ниже:

Ссылка, название, марка, описание

http://abcd.com,abcd,abcd123,abcd 123 (1g)

http://efgh.com,efgh,efgh456,efgh 456 (2 г)

http://ijkl.com,ijkl,ijkl789,ijkl 789 (3 г)

Ниже мой код:

rows = doc.xpath("//table")
       for tr in rows:
           tds = tr.xpath("//td")
           for td in tds:
               Link = td.xpath("//td[1]/a/@href")
               name = td.xpath("//td[1]//text()")
               brand = td.xpath("//td[2]//text()")
               description = td.xpath("//td[3]//text()")
       results = []
       results.append(Link)
       results.append(name)
       results.append(brand)
       results.append(description)
       for result in results:
           writer.writerow(result)

Здесь,Я не могу понять, как получить данные в указанном выше формате в CSV.

Ответы [ 2 ]

0 голосов
/ 27 мая 2018

Вы можете использовать BeautifulSoup:

from bs4 import BeautifulSoup as soup
import csv
with open('filename.csv', 'w') as f:
  write = csv.writer(f)
  header = ['Link']+[i.text for i in soup(data, 'html.parser').find_all('th')]
  final_results = [[[b.find('a')['href'], b.text] for b in i.find_all('td')] for i in soup(data, 'html.parser').find_all('tr')][1:]
  write.writerows([header]+[[b[0][0], *[i[-1] for i in b]] for b in final_results])

Выход:

Link,name,brand,description
http://abcd.com,abcd,abcd123,abcd 123 (1g)
http://efgh.com,efgh,efgh456,efgh 456 (2g)
http://ijkl.com,ijkl,ijkl789,ijkl 789 (3g)
0 голосов
/ 27 мая 2018

Попробуйте следующий подход.Каждый xpath возвращает список, так что вы можете добавить их вместе, чтобы создать строку:

from lxml import html

doc = html.fromstring(html_text)

with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)

    for tr in doc.xpath("//table"):
        tds = tr.xpath("//td")
        for td in tds:
            Link = td.xpath("//td[1]/a/@href")
            name = td.xpath("//td[1]//text()")
            brand = td.xpath("//td[2]//text()")
            description = td.xpath("//td[3]//text()")
            csv_output.writerow(Link + name + brand + description)

Предоставляя вам CSV-файл, похожий на:

http://abcd.com,http://efgh.com,http://ijkl.com,abcd,efgh,ijkl,abcd123,efgh456,ijkl789,abcd 123 (1g),efgh 456 (2g),ijkl 789 (3g)
http://abcd.com,http://efgh.com,http://ijkl.com,abcd,efgh,ijkl,abcd123,efgh456,ijkl789,abcd 123 (1g),efgh 456 (2g),ijkl 789 (3g)
http://abcd.com,http://efgh.com,http://ijkl.com,abcd,efgh,ijkl,abcd123,efgh456,ijkl789,abcd 123 (1g),efgh 456 (2g),ijkl 789 (3g)
http://abcd.com,http://efgh.com,http://ijkl.com,abcd,efgh,ijkl,abcd123,efgh456,ijkl789,abcd 123 (1g),efgh 456 (2g),ijkl 789 (3g)
http://abcd.com,http://efgh.com,http://ijkl.com,abcd,efgh,ijkl,abcd123,efgh456,ijkl789,abcd 123 (1g),efgh 456 (2g),ijkl 789 (3g)
http://abcd.com,http://efgh.com,http://ijkl.com,abcd,efgh,ijkl,abcd123,efgh456,ijkl789,abcd 123 (1g),efgh 456 (2g),ijkl 789 (3g)
http://abcd.com,http://efgh.com,http://ijkl.com,abcd,efgh,ijkl,abcd123,efgh456,ijkl789,abcd 123 (1g),efgh 456 (2g),ijkl 789 (3g)
http://abcd.com,http://efgh.com,http://ijkl.com,abcd,efgh,ijkl,abcd123,efgh456,ijkl789,abcd 123 (1g),efgh 456 (2g),ijkl 789 (3g)
http://abcd.com,http://efgh.com,http://ijkl.com,abcd,efgh,ijkl,abcd123,efgh456,ijkl789,abcd 123 (1g),efgh 456 (2g),ijkl 789 (3g)
...