如何在Python脚本中将useragent设置为QuickTime?

时间:2011-12-23 17:34:34

标签: python user-agent

如果useragent是QT,服务器只允许访问视频,如何将其添加到此脚本?

#!/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()

忽略此文本以填写发布限制。 blablablabla

2 个答案:

答案 0 :(得分:1)

您可以这样更改:

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

然后尝试:

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

而不是直接使用urllib而应该这样做。

(我不确定为什么覆盖urllib内部不起作用,但它们是内部并且戳它们并不能保证工作:()

此处还有更多信息:

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

答案 1 :(得分:1)

这实际上是在the docs中描述的。您的代码应如下所示:

#!/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)