我已经成功地将 JS 列出的网站抓取到本地 .html 文件中,但输出不足。
问题是:
- 它只生成最后一个查询(audioSource),而不生成其他请求
- 它只找到第 1 集,然后停在那里。如何让它重复直到找到结尾?
非常感谢
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))
最佳答案
这里的问题是:
- 在写入时使用
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
关于python - 尝试将网页中的JS数据输出到.html输出文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56519466/