43

问题

我在工作中使用了一个工具,它可以让我进行查询并取回 HTML 信息表。我没有任何形式的后端访问它。

如果我可以将这些信息放入电子表格中进行排序、平均等,那么这些信息会更加有用。如何将这些数据截屏到 CSV 文件中?

我的第一个想法

因为我知道 jQuery,我想我可以用它来去除屏幕上的表格格式,插入逗号和换行符,然后将整个混乱复制到记事本中并保存为 CSV。有更好的想法吗?

解决方案

是的,伙计们,这真的就像复制和粘贴一样简单。我不觉得很傻吗。

具体来说,当我粘贴到电子表格中时,我必须选择“选择性粘贴”并选择“文本”格式。否则,即使我突出显示了整个电子表格,它也会尝试将所有内容粘贴到单个单元格中。

4

11 回答 11

34
  • 在工具的 UI 中选择 HTML 表格并将其复制到剪贴板(如果可能的话
  • 将其粘贴到 Excel 中。
  • 另存为 CSV 文件

但是,这是一种手动解决方案,而不是自动化解决方案。

于 2008-11-03T16:03:57.343 回答
13

使用蟒蛇:

例如,假设您想从某个站点以 csv 格式抓取外汇报价,例如:fxquotes

然后...

from BeautifulSoup import BeautifulSoup
import urllib,string,csv,sys,os
from string import replace

date_s = '&date1=01/01/08'
date_f = '&date=11/10/08'
fx_url = 'http://www.oanda.com/convert/fxhistory?date_fmt=us'
fx_url_end = '&lang=en&margin_fixed=0&format=CSV&redirected=1'
cur1,cur2 = 'USD','AUD'
fx_url = fx_url + date_f + date_s + '&exch=' + cur1 +'&exch2=' + cur1
fx_url = fx_url +'&expr=' + cur2 +  '&expr2=' + cur2 + fx_url_end
data = urllib.urlopen(fx_url).read()
soup = BeautifulSoup(data)
data = str(soup.findAll('pre', limit=1))
data = replace(data,'[<pre>','')
data = replace(data,'</pre>]','')
file_location = '/Users/location_edit_this'
file_name = file_location + 'usd_aus.csv'
file = open(file_name,"w")
file.write(data)
file.close()

编辑:从表中获取值:示例来自:palewire

from mechanize import Browser
from BeautifulSoup import BeautifulSoup

mech = Browser()

url = "http://www.palewire.com/scrape/albums/2007.html"
page = mech.open(url)

html = page.read()
soup = BeautifulSoup(html)

table = soup.find("table", border=1)

for row in table.findAll('tr')[1:]:
    col = row.findAll('td')

    rank = col[0].string
    artist = col[1].string
    album = col[2].string
    cover_link = col[3].img['src']

    record = (rank, artist, album, cover_link)
    print "|".join(record)
于 2008-11-11T01:17:11.267 回答
11

这是我使用(当前)最新版本的 BeautifulSoup 的 python 版本,可以使用例如,

$ sudo easy_install beautifulsoup4

该脚本从标准输入读取 HTML,并以正确的 CSV 格式输出在所有表中找到的文本。

#!/usr/bin/python
from bs4 import BeautifulSoup
import sys
import re
import csv

def cell_text(cell):
    return " ".join(cell.stripped_strings)

soup = BeautifulSoup(sys.stdin.read())
output = csv.writer(sys.stdout)

for table in soup.find_all('table'):
    for row in table.find_all('tr'):
        col = map(cell_text, row.find_all(re.compile('t[dh]')))
        output.writerow(col)
    output.writerow([])
于 2013-05-22T17:11:10.133 回答
5

更容易(因为它会为您保存下次使用)...

在 Excel 中

数据/导入外部数据/新建网页查询

将带您进入 url 提示。输入您的网址,它将在页面上分隔要导入的可用表。瞧。

于 2008-11-11T03:04:50.817 回答
5

我想到了两种方法(尤其是对于我们这些没有 Excel 的人):

于 2015-01-22T07:37:25.260 回答
2

又快又脏:

从浏览器复制到 Excel,另存为 CSV。

更好的解决方案(长期使用):

用您选择的语言编写一些代码,将 html 内容拉下来,并刮出您想要的部分。您可能会在数据检索之上投入所有数据操作(排序、平均等)。这样,您只需运行您的代码并获得您想要的实际报告。

这完全取决于您执行此特定任务的频率。

于 2008-11-03T16:09:00.377 回答
2

Excel可以打开一个http页面。

例如:

  1. 点击文件,打开

  2. 在文件名下,粘贴 URL,即:如何将 HTML 表格抓取到 CSV?

  3. 点击确定

Excel 尽最大努力将 html 转换为表格。

它不是最优雅的解决方案,但确实有效!

于 2008-11-11T01:25:57.287 回答
2

使用 BeautifulSoup 的基本 Python 实现,同时考虑 rowspan 和 colspan:

from BeautifulSoup import BeautifulSoup

def table2csv(html_txt):
   csvs = []
   soup = BeautifulSoup(html_txt)
   tables = soup.findAll('table')

   for table in tables:
       csv = ''
       rows = table.findAll('tr')
       row_spans = []
       do_ident = False

       for tr in rows:
           cols = tr.findAll(['th','td'])

           for cell in cols:
               colspan = int(cell.get('colspan',1))
               rowspan = int(cell.get('rowspan',1))

               if do_ident:
                   do_ident = False
                   csv += ','*(len(row_spans))

               if rowspan > 1: row_spans.append(rowspan)

               csv += '"{text}"'.format(text=cell.text) + ','*(colspan)

           if row_spans:
               for i in xrange(len(row_spans)-1,-1,-1):
                   row_spans[i] -= 1
                   if row_spans[i] < 1: row_spans.pop()

           do_ident = True if row_spans else False

           csv += '\n'

       csvs.append(csv)
       #print csv

   return '\n\n'.join(csvs)
于 2015-03-26T10:34:00.617 回答
1

这是一个经过测试的示例,它结合了 grequest 和 soup 从结构化网站下载大量页面:

#!/usr/bin/python

from bs4 import BeautifulSoup
import sys
import re
import csv
import grequests
import time

def cell_text(cell):
    return " ".join(cell.stripped_strings)

def parse_table(body_html):
    soup = BeautifulSoup(body_html)
    for table in soup.find_all('table'):
        for row in table.find_all('tr'):
            col = map(cell_text, row.find_all(re.compile('t[dh]')))
            print(col)

def process_a_page(response, *args, **kwargs): 
    parse_table(response.content)

def download_a_chunk(k):
    chunk_size = 10 #number of html pages
    x = "http://www.blahblah....com/inclusiones.php?p="
    x2 = "&name=..."
    URLS = [x+str(i)+x2 for i in range(k*chunk_size, k*(chunk_size+1)) ]
    reqs = [grequests.get(url, hooks={'response': process_a_page}) for url in URLS]
    resp = grequests.map(reqs, size=10)

# download slowly so the server does not block you
for k in range(0,500):
    print("downloading chunk ",str(k))
    download_a_chunk(k)
    time.sleep(11)
于 2017-04-12T22:47:57.350 回答
0

你试过用excel打开吗?如果您将 excel 中的电子表格另存为 html,您将看到 excel 使用的格式。从我编写的一个网络应用程序中,我吐出了这种 html 格式,以便用户可以导出到 excel。

于 2008-11-03T16:09:18.660 回答
0

如果您正在屏幕抓取并且您尝试转换的表格具有给定的 ID,您总是可以对 html 进行正则表达式解析以及一些脚本来生成 CSV。

于 2008-11-03T17:09:22.110 回答