【发布时间】:2018-01-29 10:40:52
【问题描述】:
我在下面有这段代码,可以在每个循环上下载文件。 我想做的是在每个循环中它应该将文件提取到相应的文件夹中。 当前发生的事情是它保存每个文件夹中的所有文件并覆盖具有相同名称的文件。
任何帮助将不胜感激。
import os
import requests
import zipfile, StringIO
from bs4 import BeautifulSoup
# Here were add the login details to be submitted to the login form.
payloads = [
{'USERNAME': '1111','PASSWORD': '1111','option': 'login'},
{'USERNAME': '2222','PASSWORD': '2222','option': 'login'},
{'USERNAME': '3333','PASSWORD': '3333','option': 'login'},
{'USERNAME': '4444','PASSWORD': '4444','option': 'login'},
]
folders = [r"C:\temp\1111", r"C:\temp\2222", r"C:\temp\3333", r"C:\temp\4444"]
#Possibly need headers later.
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
base_url = "https://service.rl360.com/scripts/customer.cgi/SC/servicing/"
# Use 'with' to ensure the session context is closed after use.
for payload in payloads:
with requests.Session() as s:
p = s.post('https://service.rl360.com/scripts/customer.cgi?option=login', data=payload)
# Get the download page to scrape.
r = s.get('https://service.rl360.com/scripts/customer.cgi/SC/servicing/downloads.php?Folder=DataDownloads&SortField=ReportDate&SortOrder=Ascending', stream=True)
content = r.text
soup = BeautifulSoup(content, 'lxml')
#Now i get the most recent download URL.
download_url = soup.find_all("a", {'class':'tabletd'})[-1]['href']
#now we join the base url with the download url.
download_docs = s.get(base_url + download_url, stream=True)
print "Checking Content"
content_type = download_docs.headers['content-type']
print content_type
print "Checking Filename"
content_name = download_docs.headers['content-disposition']
print content_name
print "Checking Download Size"
content_size = download_docs.headers['content-length']
print content_size
#This is where we extract and download the specified xml files.
z = zipfile.ZipFile(StringIO.StringIO(download_docs.content))
print "---------------------------------"
print "Downloading........."
for folder in folders:
z.extractall(folder)
#Now we save the files to the specified location.
print "Download Complete"
【问题讨论】:
-
使用 z.read() 或 z.readstr() 函数逐个文件提取文件并根据需要更改其路径和/或名称。 extractall() 覆盖现有文件有什么奇怪的?如果在每个 ZIP 中它们的名称相同,它们将被覆盖。就这么简单。
-
您在这里所做的是将相同的 ZIP 提取到所有指定的文件夹。因此,必须重新设计循环以遵循 ZIP 的内容,而不是相反。当然,假设这就是您想要实现的目标。您始终可以仅指定“C:\temp”以将整个 ZIP 提取到(不需要循环),然后处理产生的混乱。
-
问题是我使用了四个不同的登录名,每个都有文件,这些文件可能与另一个帐户中的文件同名。
标签: python python-2.7 for-loop directory zipfile