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