我有一个在网页上搜索图像的python脚本,它应该将它们下载到名为“已下载”的文件夹中。最后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)
它会打开我电脑上的已下载文件夹和其中的misc文件夹。它会给出一个回溯错误。回溯:
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)
发布于 2018-12-20 06:07:51
看起来你的downloadList包含了一些不是图片的URL。相反,您可以在HTML中查找任何<img>
标记:
downloadList = bsObj.find_all('img')
然后使用此命令下载这些图像:
for download in downloadList:
fileUrl = getAbsoluteURL(baseUrl,download["src"])
r = requests.get(fileUrl, allow_redirects=True)
filename = os.path.join(downloadDirectory, fileUrl.split('/')[-1])
open(filename, 'wb').write(r.content)
编辑:我已经更新了filename = ...
行,以便它将同名文件写入字符串downloadDirectory
中的目录。顺便说一下,Python变量的常规约定是不使用驼峰大小写。
https://stackoverflow.com/questions/53859707
复制相似问题