【问题标题】:Python table scrapePython 表格抓取
【发布时间】:2018-08-28 02:18:41
【问题描述】:

我正在尝试从https://markets.wsj.com/ 中抓取“主要股票指数表”,并希望将其保存到我桌面上的文件夹中。这是我目前所拥有的:

import urllib.request
import json
import re

html = urllib.request.urlopen("https://markets.wsj.com/").read().decode('utf8')
json_data = re.findall(r'pws_bootstrap:(.*?)\s+,\s+country\:', html, re.S)
data = json.loads(json_data[0])

filename = "C:\Users\me\folder\sample.csv"
f = open(filename, "w")

for numbers in data['chart']:
    for obs in numbers['Major Stock Indexes']:
        f.write(str(obs['firstCol']) + "," + str(obs['dataCol']) + "," + str(obs['dataCol priceUp']) + str(obs['dataCol lastb priceUp']) + "\n")

print(obs.keys())

我收到错误:IndexError: list index out of range

有什么想法可以解决我的问题吗?

【问题讨论】:

  • 你能添加整个堆栈跟踪并在代码中添加一些打印吗?
  • 我发现你的json_data是一个空列表[],你应该使用像bs4这样的抓取工具

标签: python python-3.x


【解决方案1】:

你的json_data是一个空列表[],你应该使用像bs4这样的抓取工具,如下所示:

from bs4 import BeautifulSoup
import urllib.request
html = urllib.request.urlopen("https://markets.wsj.com/").read().decode('utf8')
soup = BeautifulSoup(html, 'html.parser')  # parse your html
t = soup.find('table', {'summary': 'Major Stock Indexes'})  # finds tag table with attribute summary equals to 'Major Stock Indexes'
tr = t.find_all('tr')  # get all table rows from selected table
row_lis = [i.find_all('td') if i.find_all('td') else i.find_all('th') for i in tr if i.text.strip()]  # construct list of data
print([','.join(x.text.strip() for x in i) for i in row_lis])

输出:

[',Last,Change,% CHG,',
 'DJIA,26049.64,259.29,1.01%',
 'Nasdaq,8017.90,71.92,0.91%',
 'S&P 500,2896.74,22.05,0.77%',
 'Russell 2000,1728.41,2.73,0.16%',
 'Global Dow,3105.09,3.73,0.12%',
 'Japan: Nikkei 225,22930.58,130.94,0.57%',
 'Stoxx Europe 600,385.57,2.01,0.52%',
 'UK: FTSE 100,7577.49,14.27,0.19%']

现在您可以遍历此列表并将其存储在 csv 中,而不是打印它。

【讨论】:

  • 完美!谢谢
  • 如何将打印行转换为可以写入 csv 文件的格式?
  • 为此您可以使用内置的csv 模块并按照文档中的说明使用csv.writer()
  • 对不起,我对 python 不是很好。我必须用“csv.writer”替换“打印”,还是我需要做其他事情?
猜你喜欢
  • 1970-01-01
  • 2021-07-08
  • 2021-01-04
  • 2020-04-02
  • 1970-01-01
  • 2016-01-31
  • 2015-12-12
  • 2018-10-15
相关资源
最近更新 更多