python - Python 表格抓取
问题描述
我正在尝试从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
:
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 中而不是打印它。
推荐阅读
- php - .htaccess 的问题 - RewriteRule 将新 URL 附加到旧 URL
- c# - Android - 通过 CSOM 或 REST 连接到 MS Sharepoint 会导致本地文件系统 UnauthorizedAccessException
- azure-devops - 使用 subst 的 Azure Pipeline 构建代理
- api - GraphQL 查询中的分组
- python - 如何不在 Dash 中显示默认的 dcc.graph 模板?
- android - 如何在运行时从 Android 应用程序读取 jar 文件中保存的 3rd 方资源列表
- docker - Docker 容器 - 更新入口点文件
- python - 如何在前一个会话超时后通过 pyghmi.impi.command.Command 打开一个新的 pyghmi 会话?
- javascript - 占三个单词数组中最长的决胜局
- flutter - Flutter web 元素抛出 elementnotInteractable 异常