刚开始想通过页面url,使用bs4获取html页面然后解析,然后发现url路径是不变的。最后找到路径直接给我返回json字符串了。如下:
#获取百度1000条格言
import urllib.request
import json
url="https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?from_mid=1&format=json&ie=utf-8&oe=utf-8&subtitle=%E6%A0%BC%E8%A8%80&query=%E6%A0%BC%E8%A8%80&rn=8&resource_id=6844&cb=jQuery110201627604384422121_1532592711270&_=1532592711285&pn="
#这里返回的是json字符串(多了一丢丢杂质)
def getHtml(i):
response = urllib.request.urlopen(url+str(8*(i-1)))
buff = response.read()
html = buff.decode('utf-8')
html=html[html.index('{'):-2]
jsonData=json.loads(html)
return jsonData
with open("d:/motto.txt",'a+') as file:
for i in range(1,126):
json_data=getHtml(i)['data'][0]['disp_data']#得到一个包含格言和作者的字典的列表,嵌套有点多,找起来都有点眼花
for dic in json_data:
file.write(dic['ename'])
file.write('——')
file.write(dic['author']+'\n')