Skip to main content
 首页 » 编程设计

python之如何在通过网络抓取创建的 json 文件中组织数据

2024年12月31日8webabcd

我正在尝试从雅虎新闻获取文章标题并将其组织在一个 json 文件中。当我将数据转储到 json 文件时,它看起来难以阅读。我将如何组织数据,是在转储之后还是从头开始?

这是一个网络抓取项目,我必须在其中获取热门新闻文章及其正文并将它们导出到一个 json 文件,然后该文件可以发送到其他人的程序。目前,我只是在努力从雅虎财经主页获取标题。

import requests 
import json 
from bs4 import BeautifulSoup 
 
#Getting webpage 
page = requests.get("https://finance.yahoo.com/") 
soup = BeautifulSoup(page.content, 'html.parser') #creating instance of class to parse the page 
#Getting article title 
title = soup.find_all(class_="Mb(5px)") 
desc = soup.find_all(class_="Fz(14px) Lh(19px) Fz(13px)--sm1024 Lh(17px)--    sm1024 LineClamp(3,57px) LineClamp(3,51px)--sm1024 M(0)") 
#Getting article bodies 
page2 = requests.get("https://finance.yahoo.com/news/warren-buffett-suggests-read-19th-204800450.html") 
soup2 = BeautifulSoup(page2.content, 'html.parser') 
body = soup.find_all(class_="canvas-atom canvas-text Mb(1.0em) Mb(0)--sm  
Mt(0.8em)--sm", id="15") 
 
 
#Organizing data for export 
data = {'title1': title[0].get_text(), 
    'title2': title[1].get_text(), 
    'title3': title[2].get_text(), 
    'title4': title[3].get_text(), 
    'title5': title[4].get_text()}   
 
#Exporting the data to results.json 
with open("results.json", "w") as write_file: 
  json.dump(str(data), write_file) 

这是最终写入 json 文件的内容(在撰写本文时):

"{'title1': 'These US taxpayers face higher payments thanks to new law',  
'title2': 'These 12 Stocks Are the Best Values in 2019, According to Pros  
Who\u2019ve Outsmarted the Market', '\\ntitle3': 'The Best Move You Can      
Make With Your Investments in 2019, According to 5 Market Professionals',  
'title4': 'The auto industry said goodbye to a lot of cars in 2018',  
'title5': '7 Stock Picks From Top-Rated Wall Street Analysts'}" 

我想编写代码以在单独的行上显示每篇文章的标题,并删除出现在中间的随机“\”。

请您参考如下方法:

我已经运行了您的代码,但没有得到与您相同的结果。您已经定义了一个常量“title3”,但是您得到了“\n”,在我的例子中我实际上没有得到。顺便说一句,你得到/是因为你没有像 'utf8' 那样正确编码它,并且 ascii 确保设置为 false。我会建议两个变化,比如 - 'lxml' 解析器而不是 'html.parser' 和这个代码片段:

with open("results.json", "w",encoding='utf8') as write_file: 
    json.dump(str(data), write_file ,ensure_ascii=False) 

这对我来说完全有效/的排除和 ascii 问题也得到了解决。