如果我使用urllib2打开文件,如下所示:
remotefile = urllib2.urlopen('http://example.com/somefile.zip')
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法来获取文件名,然后解析原始URL?
编辑:将openfile更改为urlopen ...不确定是怎么回事.
编辑2:我最终使用:
filename = url.split('/')[-1].split('#')[0].split('?')[0]
Run Code Online (Sandbox Code Playgroud)
除非我弄错了,否则这也应该删除所有潜在的查询.
我是 Python 新手,发现了一个下载数据并将数据保存为 demofile.csv 的代码
import requests
url = "https://example.com/demofile"
r = requests.get(url)
filename = url.split('/')[-1]
with open(filename+".csv", "wb") as code:
code.write(r.content)
Run Code Online (Sandbox Code Playgroud)
现在,我不想明确指定任何名称。 我只希望通过 Python 脚本打开该 URL,并使用默认名称和类型(我们手动下载文件时出现的名称和类型)下载文件。
另外,该文件应该保存在其他目录中,而不是保存 python 代码的文件夹中。
请在这方面提供帮助。
我写了一个小程序,从NOAA下载最新的每日潮汐图,在包含潮汐信息的图像上添加一个文本表,然后将此图像设置为我的桌面壁纸.
from bs4 import BeautifulSoup
import Image, ImageDraw, ImageFont
from urllib import urlretrieve
import urllib2
import time
import ctypes
import sys
import os
import datetime
import traceback
def Fetch_tideGraph():
# Fetch the Tides Graph .gif
#
# Fetch the Station Home Page
try:
url = 'http://tidesandcurrents.noaa.gov/noaatidepredictions/viewDailyPredictions.jsp?Stationid=8637689'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
# Find the Url to the tides graph
ImgElement = str(soup.find_all('input', { "alt" : "Daily Tide Prediction graphical plot" }))
soup = BeautifulSoup(ImgElement)
tag = soup.input …
Run Code Online (Sandbox Code Playgroud)