Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将beautifulsoup web摘要保存为json_Python_Json_Python 3.x_Beautifulsoup - Fatal编程技术网

Python 将beautifulsoup web摘要保存为json

Python 将beautifulsoup web摘要保存为json,python,json,python-3.x,beautifulsoup,Python,Json,Python 3.x,Beautifulsoup,PythonNoob在这里,我已经设法从维基百科抓取了一个公司列表,我如何将输出保存为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, 'h

PythonNoob在这里,我已经设法从维基百科抓取了一个公司列表,我如何将输出保存为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
在表中,您将检索所有您感兴趣的对象,您甚至可以在选择中添加更多粒度,以便仅从HTML中获取名称。 然后做:

使用以下命令:

导入请求 从bs4导入BeautifulSoup 导入json url=https://en.wikipedia.org/wiki/List_of_companies_traded_on_the_JSE responce=requests.geturl soup=beautifulsoupresponse.text,“html.parser” table=soup.findAll'table',{'class':wikitable sortable} 表=[表中x的strx.text] json_text=json.dumpstables 打开'companys.json','w'作为json_文件: json_file.writejson_text
这应该能奏效。虽然我不确定您将如何处理它,因为这是表中所有数据的列表。

您应该使用导入json,而不是JSONThank!我实际上想做的是将数据保存在一个CSV文件中,其中包含行的标题,我该怎么做呢?再次感谢您。filename='jse.csv'和openfilename,'wb'作为f:w=csv.dictwriter,['company','Symbol','url','lines']w.writeheader for tables in tables:w.writerowtable类似的内容?
with open('data.json', 'w') as outfile:
    json.dump(table, outfile)