python - 将 beautifulsoup 网页抓取保存到 json
问题描述
python noob here,我已经设法从 Wikipedia 中抓取了公司列表,如何将输出保存为 JSON 文件?
import requests
from bs4 import BeautifulSoup
import JSON
url = "https://en.wikipedia.org/wiki/List_of_companies_traded_on_the_JSE"
responce = requests.get(url)
soup = BeautifulSoup(responce.text, 'html.parser')
tables = soup.findAll('table', {'class':"wikitable sortable"})
for table in soup.find_all('table', {'class':"wikitable sortable"}):
print(table.text
解决方案
用这个:
import requests
from bs4 import BeautifulSoup
import json
url = "https://en.wikipedia.org/wiki/List_of_companies_traded_on_the_JSE"
responce = requests.get(url)
soup = BeautifulSoup(responce.text, 'html.parser')
table = soup.findAll('table', {'class':"wikitable sortable"})
tables = [str(x.text) for x in table]
json_text = json.dumps(tables)
with open('companies.json', 'w') as json_file:
json_file.write(json_text)
这应该够了吧。虽然我不确定你将如何处理它,因为这是表中所有数据的列表。
推荐阅读
- java - 比较 Java 中的 NULL 值
- c# - 在运行时将 X 个带有 SelectedItem 的组合框添加到 DataGrid (WPF)
- c# - .Net Core Api - 基于请求值的自定义 JSON 解析器
- image - 可以使用 ARM 模板获取订阅中的图像列表吗?
- c++ - dynamic library issue: dlsym() failing to find smbol
- python - 使用特定模型通过 Tinkerpop 将(数百万行)数据导入 Janusgraph 的最佳方式
- android - 异步和跳帧
- multithreading - 定时器不能从另一个线程 Qt 停止
- c++ - 大数组和的优化(多线程)
- sql-server - 如何使用别名更正查询