2011-12-23 83 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