2011-12-23 102 views
0

如果useragent是QT,服务器只允许访问视频,如何将其添加到此脚本中?如何在Python脚本中将useragent设置为QuickTime?

#!/usr/bin/env python 
from os import pardir, rename, listdir, getcwd 
from os.path import join 
from urllib import urlopen, urlretrieve, FancyURLopener 
class MyOpener(FancyURLopener): 
    version = 'QuickTime/7.6.2 (verqt=7.6.2;cpu=IA32;so=Mac 10.5.8)' 

def main(): 
# Set up file paths. 
data_dir = 'data' 
ft_path = join(data_dir, 'titles.txt') 
fu_path = join(data_dir, 'urls.txt') 

# Open the files 
try: 
    f_titles = open(ft_path, 'r') 
    f_urls = open(fu_path, 'r') 
except: 
    print "Make sure titles.txt and urls.txt are in the data directory." 
    exit() 

# Read file contents into lists. 
titles = [] 
urls = [] 
for l in f_titles: 
    titles.append(l) 
for l in f_urls: 
    urls.append(l) 

# Create a dictionary and download the files. 
downloads = dict(zip(titles, urls)) 
for title, url in downloads.iteritems(): 
    fpath = join(data_dir, title.strip().replace('\t',"").replace(" ", "_")) 
    fpath += ".mov" 
    urlretrieve(url, fpath) 

if __name__ == "__main__": main() 

忽略此项,填写发布限制文字。相反

opener = MyOpener() 
opener.retrieve(url, fpath) 

直接使用urllib模块和应该做的伎俩:blablablabla

回答

1

你的代码应该是这样的:

#!/usr/bin/env python 
import urllib 

from os import pardir, rename, listdir, getcwd 
from os.path import join 


class MyOpener(urllib.FancyURLopener): 
    version = 'QuickTime/7.6.2 (verqt=7.6.2;cpu=IA32;so=Mac 10.5.8)' 

# This line tells urllib.urlretrieve and urllib.urlopen to use your MyOpener 
# instead of the default urllib.FancyOpener 
urllib._urlopener = MyOpener() 

def main(): 
    # lots of stuff 
    for title, url in downloads.iteritems(): 
     fpath = join(data_dir, title.strip().replace('\t',"").replace(" ", "_")) 
     fpath += ".mov" 
     urllib.urlretrieve(url, fpath) 
1

你可以这样改变它:

http://wolfprojects.altervista.org/changeua.php

然后尝试。

(我不知道为什么压倒一切的urllib内部不工作,但他们内部和他们戳不guaranteened工作:()

而且更多的信息在这里:

http://docs.python.org/library/urllib.html#urllib.URLopener

+0

我根本不知道Python ... – WaterBearer 2011-12-23 18:07:20

+0

我做了以下但文件仍未下载'从urllib导入urlopen,urlretrieve,FancyURLopener 类MyOpener(FancyURLopener): \t version ='QuickTime/7.6.2(verqt = 7.6.2; cpu = IA32 ;因此= Mac 10.5.8)'' – WaterBearer 2011-12-23 18:23:05

+0

请发布完整的源代码鳕你正在做什么 - 否则它是不可能的帮助 – 2011-12-24 12:28:53