我有一个python脚本,可以在网页上搜索图像,它应该把它们下载到名为“download”的文件夹中。最后2-3行是有问题的,我不知道如何写正确的'与开放'代码。你知道吗
脚本的最大部分很好,第42-43行给出了一个错误
import os
import requests
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 = requests.get("http://www.pythonscraping.com")
bsObj = BeautifulSoup(html.content, 'html.parser')
downloadList = bsObj.find_all(src=True)
for download in downloadList:
fileUrl = getAbsoluteURL(baseUrl,download["src"])
if fileUrl is not None:
print(fileUrl)
with open(fileUrl, getDownloadPath(baseUrl, fileUrl, downloadDirectory), 'wb') as out_file:
out_file.write(fileUrl.content)
它会打开“我的电脑”上的“下载”文件夹和其中的“杂项”文件夹。它给出了一个回溯错误。 回溯:
http://pythonscraping.com/misc/jquery.js?v=1.4.4
Traceback (most recent call last):
File "C:\Python36\kodovi\downloaded.py", line 43, in <module>
with open(fileUrl, getDownloadPath(baseUrl, fileUrl, downloadDirectory), 'wb
') as out_file:
TypeError: an integer is required (got type str)
似乎你的下载列表包含了一些不是图片的URL。您可以在HTML中查找任何
<img>
标记:然后使用此选项下载这些图像:
编辑:我已经更新了
filename = ...
行,这样它就可以将同名文件写入到downloadDirectory
字符串中的目录中。顺便说一下,Python变量的常规惯例是不使用camel case。你知道吗相关问题 更多 >
编程相关推荐