马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 uranometria 于 2020-11-4 10:03 编辑
如题!!!
用Request时候会报错:
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\PYTHON\music.py", line 38, in <module>
get_songs_file()
File "C:\Users\Administrator\Desktop\PYTHON\music.py", line 35, in get_songs_file
urllib.request.urlretrieve(url=req, filename=each)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 245, in urlretrieve
url_type, path = _splittype(url)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\urllib\parse.py", line 988, in _splittype
match = _typeprog.match(url)
TypeError: expected string or bytes-like object
========================================================================
现在报错改为了:
ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。
完整代码如下:import urllib.request
import time
import os
import re
#下载地址:https://freepd.com/music/Silly%20Intro.mp3
path = 'C:\\Users\\Administrator\\Documents\\cache'
os.chdir(path)
url = 'https://freepd.com/upbeat.php'
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0'
}
def get_songs_name():
req = urllib.request.Request(url=url, headers=headers)
result = urllib.request.urlopen(req)
content = result.read().decode('utf-8')
string = re.compile('<B>\w*\s\w*</B>')
all_songs = string.findall(content)
all_songs_name = []
for each in all_songs:
all_songs_name.append(each[3:-4] + '.mp3')
return all_songs_name
def get_songs_file():
for each in get_songs_name():
path = each.replace(" ", "%20")
download_url = "https://freepd.com/music/" + str(path)
req = urllib.request.Request(url=download_url, headers=headers)
result = urllib.request.urlopen(req)
urllib.request.urlretrieve(url=req, filename=each) #直接使用download_url可以正常下载 改为req则不行,报错。
time.sleep(20)
get_songs_file()
一般不需要,urlretrieve一般是针对文件get,文件一般不看ua。而如果是get网页或json数据会看ua。
|