import requests
import parsel
headers = {
'Referer': 'https://www.ximalaya.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.35'
}
def download_one_music(song_id, name):
api_url = 'https://www.ximalaya.com/revision/play/v1/audio?id='+song_id+'&ptype=1'
response = requests.get(api_url, headers=headers)
src = response.json()['data']['src']
print(src)
response = requests.get(src,headers=headers)
print(response)
with open(name + '.m4a',mode='wb')as f:
f.write(response.content)
response = requests.get('https://www.ximalaya.com/album/68559551',headers=headers)
html =response.text
selector = parser.Selector(html)
lis = selector.css('li._nO')
for li in lis:
title = li.css('div.text._nO a::attr(title)').get()
href = li.css('div.text._nO a::attr(title)').get()
song_id = href.split('/')[-1]
print(song_id,title)
在这段代码中存在一个变量命名错误,将 parser
写成了 parsel
,导致调用 Selector()
函数时出现了一个 NameError
异常。你需要将 parsel
改成 parser
即可解决这个问题。
除此之外,还有一些需要改进的地方:
第 22 行中的 href
变量赋值错误,应该使用 li.css('div.text._nO a::attr(href)').get()
来获取链接地址。
第 24 行中的 print(song_id,title)
应该放在下载音乐前面,以便在下载过程中知道当前正在下载哪个音乐。
在下载音乐时,强烈建议使用异常处理机制,对可能出现的网络请求失败、文件读写异常等问题进行捕获和处理。
下面是修改后的代码:
import requests
import parsel
headers = {
'Referer': 'https://www.ximalaya.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.35'
}
def download_one_music(song_id, name):
api_url = 'https://www.ximalaya.com/revision/play/v1/audio?id=' + song_id + '&ptype=1'
response = requests.get(api_url, headers=headers)
src = response.json()['data']['src']
print(src)
response = requests.get(src, headers=headers)
if response.status_code != 200:
print('下载音乐失败:', name)
return
with open(name + '.m4a', mode='wb') as f:
f.write(response.content)
print('成功下载音乐:', name)
response = requests.get('https://www.ximalaya.com/album/68559551', headers=headers)
html = response.text
selector = parsel.Selector(html)
lis = selector.css('li._nO')
for li in lis:
title = li.css('div.text._nO a::attr(title)').get()
href = li.css('div.text._nO a::attr(href)').get()
song_id = href.split('/')[-1]
print(song_id, title)
download_one_music(song_id, title)
在修改后的代码中,我们对下载音乐时可能出现的异常进行了处理,并且将下载成功或失败的消息打印出来,让用户能够及时了解下载情况。
不知道你这个问题是否已经解决, 如果还没有解决的话:x = 7
i = 1
flag = 0
while i <=100:
if (x%2 == 1) and (x%3 == 2) and (x%5 == 4) and (x%6 == 5):
flag = 1
else:
x = 7*(i+1)
i += 1
if flag == 1:
print (“你的阶乘是:%d”%(x))
else:
print(“在您指定的范围内找不到答案!”)
执行结果:
你的阶乘是:119