【发布时间】:2014-10-25 18:22:31
【问题描述】:
我在 SO 上搜索了很多类似的问题,但没有找到与我的案例完全匹配的问题。
我正在尝试使用 python 2.7 下载视频
这是我下载视频的代码
import urllib2
from bs4 import BeautifulSoup as bs
with open('video.txt','r') as f:
last_downloaded_video = f.read()
webpage = urllib2.urlopen('http://*.net/watch/**-'+last_downloaded_video)
soup = bs(webpage)
a = []
for link in soup.find_all('a'):
if link.has_attr('data-video-id'):
a.append(link)
#try just with first data-video-id
id = a[0]['data-video-id']
webpage2 = urllib2.urlopen('http://*/video/play/'+id)
soup = bs(webpage2)
string = str(soup.find_all('script')[2])
print string
url = string.split(': ')[1].split(',')[0]
url = url.replace('"','')
print url
print type(url)
video = urllib2.urlopen(url).read()
filename = "video.mp4"
with open(filename,'wb') as f:
f.write(video)
此代码给出了一个未知的 url 类型错误。回溯是
Traceback (most recent call last):
File "naruto.py", line 26, in <module>
video = urllib2.urlopen(url).read()
File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 427, in _open
'unknown_open', req)
File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1247, in unknown_open
raise URLError('unknown url type: %s' % type)
urllib2.URLError: <urlopen error unknown url type: 'http>
但是,当我将相同的 url 存储在变量中并尝试从终端下载它时,不会显示错误。 我对问题所在感到困惑。 我有一个类似的问题in python mailing list
【问题讨论】:
-
print url语句的输出是什么?url[0]是什么?它似乎是“'http”(注意字符串开头的额外单引号),在这种情况下,您需要从 URL 中删除它。如果您提供您正在使用的实际 URL,可能会更容易。 -
打印网址给出“http://oose.io/20a6b47da772361b05d1c4ad3cf1723a5209d0cc/video.mp4”(火影忍者剧集的链接,工作正常)
-
我故意在 // 后面留了一个空格,因为 http 没有显示出来。
标签: python python-2.7 beautifulsoup urllib2 ubuntu-14.04