tfp = open(filename, 'wb')
OSError: [Errno 22} Invalid argument: 'downloaded/misc/jquery.js?v=1.4.4'
有人能帮我解决这个错误吗?我想这与jquery.js?v=1.4.4
无效有关。我是python的新手;如果我遗漏了一些显而易见的东西,我很抱歉。在
代码如下:
import os
from urllib.request import urlretrieve
from urllib.request import urlopen
from bs4 import BeautifulSoup
downloadDirectory = "downloaded"
baseUrl = "http://pythonscraping.com"
def getAbsoluteURL(baseUrl, source):
if source.startswith("http://www."):
url = "http://"+source[11:]
elif source.startswith("http://"):
url = source
elif source.startswith("www."):
url = source[4:]
url = "http://"+source
else:
url = baseUrl+"/"+source
if baseUrl not in url:
return None
return url
def getDownloadPath(baseUrl, absoluteUrl, downloadDirectory):
path = absoluteUrl.replace("www.", "")
path = path.replace(baseUrl, "")
path = downloadDirectory+path
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
return path
html = urlopen("http://www.pythonscraping.com")
bsObj = BeautifulSoup(html, "html.parser")
downloadList = bsObj.findAll(src=True)
for download in downloadList:
fileUrl = getAbsoluteURL(baseUrl, download["src"])
if fileUrl is not None:
print(fileUrl)
urlretrieve(fileUrl, getDownloadPath(baseUrl, fileUrl, downloadDirectory))
下载/杂项/jquery.js?v=1.4.4不是有效的文件名。 我认为一个更好的解决方案是:
对于函数
urlretrieve(url, filename, reporthook, data)
, 为filename
参数提供的参数必须是操作系统上的有效文件名。在在这种情况下,当你跑的时候
您为
url
提供的参数是“http://pythonscraping.com/misc/jquery.js?v=1.4.4”,您为filename
提供的参数是“download/misc”/jquery.js?v=1.4.4英寸。在““jquery.js?v=1.4.4“我认为不是有效的文件名。在
解决方案:在
^{pr2}$getDownloadPath
函数中,将return path
更改为相关问题 更多 >
编程相关推荐