Bro*_*123 6 python url http urllib
我想从互联网页面下载所有文件,实际上是所有图像文件.我发现'urllib'模块是我需要的.如果您知道文件名,似乎有一种下载文件的方法,但我不知道.
urllib.urlretrieve('http://www.example.com/page', 'myfile.jpg')
Run Code Online (Sandbox Code Playgroud)
是否有方法从页面下载所有文件,并可能返回一个列表?
这里有一个小例子让你开始使用BeautifulSoup进行这种练习 - 你给这个脚本一个URL,它将打印出以或以以下结尾src
的img
标签属性从该页面引用的图像的URL :jpg
png
import sys, urllib, re, urlparse
from BeautifulSoup import BeautifulSoup
if not len(sys.argv) == 2:
print >> sys.stderr, "Usage: %s <URL>" % (sys.argv[0],)
sys.exit(1)
url = sys.argv[1]
f = urllib.urlopen(url)
soup = BeautifulSoup(f)
for i in soup.findAll('img', attrs={'src': re.compile('(?i)(jpg|png)$')}):
full_url = urlparse.urljoin(url, i['src'])
print "image URL: ", full_url
Run Code Online (Sandbox Code Playgroud)
然后您可以使用urllib.urlretrieve
下载指向的每个图像full_url
,但在那个阶段您必须决定如何命名它们以及如何处理下载的图像,这在您的问题中未指定.