我已经成功地将JS列出的网站刮到了本地.html文件中,但是输出不足。
问题是:
非常感谢
import requests
import json
from bs4 import BeautifulSoup
JSONDATA = requests.request("GET", "https://thisiscriminal.com/wp-json/criminal/v1/episodes?posts=1000000&page=1")
JSONDATA = JSONDATA.json()
for line in JSONDATA['posts']:
soup = BeautifulSoup(line['episodeNumber'],'lxml')
soup = BeautifulSoup(line['title'],'lxml')
soup = BeautifulSoup(line['image']['large'],'lxml')
soup = BeautifulSoup(line['excerpt']['long'],'lxml')
soup = BeautifulSoup(line['audioSource'],'lxml')
with open("output1.html", "w") as file:
file.write(str(soup))
答案 0 :(得分:1)
这里的问题是:
w
,它将整个文件替换为更新的文本。soup
。bs4
模块来解析json数据。您可以做的是:
安装pandas
模块并创建一个数据框。
使用 pip :pip install pandas
或 conda :conda install pandas
安装它。
然后,您可以使用dataframe
并随意使用它。
import requests
import json
import pandas as pd
import os
JSONDATA = requests.request("GET", "https://thisiscriminal.com/wp-json/criminal/v1/episodes?posts=1000000&page=1")
JSONDATA = JSONDATA.json()
df = pd.DataFrame(JSONDATA)
filename = 'Output.txt'
os.mknod(filename) #create the filename above.
with open(filename, 'a') as fopen:
for i in range(len(df)):
fopen.writelines(df.posts[i]['episodeNumber']+'\n')
fopen.writelines(df.posts[i]['title']+'\n')
fopen.writelines(df.posts[i]['image']['large']+'\n')
fopen.writelines(df.posts[i]['excerpt']['long']+'\n')
fopen.writelines(df.posts[i]['audioSource']+'\n')
fopen.writelines("\n")
fopen.close()
这是您想要的完整代码。
另外,您可以使用print(df.head())
来查看数据框如何将值存储为字典并执行更多操作。
您可以看到整个文本here
答案 1 :(得分:1)
使用pandas
库,将数据保存到当前项目目录的CSV
文件中
import requests
import pandas as pd
resp = requests.get("https://thisiscriminal.com/wp-json/criminal/v1/episodes?posts=1000000&page=1").json()
df = pd.DataFrame(resp['posts'], columns=['episodeNumber', 'title', 'image','excerpt','audioSource'])
#it will save data into post csv file and stored in current project directory
df.to_csv("posts.csv")