问题

我在工作中使用一个工具来进行查询并获取 HTML 信息表。我没有任何后端访问权限。

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

我的第一个想法

因为我了解 jQuery,所以我想我可以用它来去掉屏幕上的表格格式,插入逗号和换行符,然后将整个乱七八糟的内容复制到记事本中并另存为 CSV。 还有更好的想法吗?

解决方案

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

具体来说,当我粘贴到电子表格中时,我必须选择“糊状特殊”,然后选择“文本”。否则,即使我突出显示了整个电子表格,它也试图将所有内容粘贴到一个单元格中。

有帮助吗?

解决方案

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

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

其他提示

使用python:

例如,想象一下你想要从某个网站获取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)

这是我使用(当前)最新版本的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([])

更简单(因为它会在下次为您保存)...

在Excel中

数据/导入外部数据/新Web查询

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

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

又快又脏:

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

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

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

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

Excel可以打开http页面。

例如:

  1. 点击文件,打开

  2. 在文件名下,粘贴网址即:如何将HTML表格刮到CSV?

  3. 点击确定

  4. Excel会尽力将html转换为表格。

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

使用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)

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

#!/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)

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top