通过HTTP连接获取YouTube搜索结果
我一直在用下面这个函数来获取YouTube的搜索结果:
from urllib import urlencode
from urllib2 import urlopen
def fetch(search_query):
url = 'http://www.youtube.com/results?'
args = urlencode({'search_query':search_query})
conn = urlopen(url,args)
data = conn.read()
conn.close()
return data
最近在某些情况下,它开始返回“空结果”,这让我不得不修改我的代码:
from urllib import urlencode
from urllib2 import urlopen
def fetch(search_query):
url = 'http://www.youtube.com/results?'
args = urlencode({'search_query':search_query})
while True:
conn = urlopen(url,args)
data = conn.read()
conn.close()
if 'results?' in data:
break
return data
正如你所看到的,我使用了 'results?'
来区分有效和无效的搜索结果。
还有一个显著的区别(其实有很多)出现在获取的HTML的开头:
- 有效结果:
yt.www.masthead.sizing.runBeforeBodyIsReady(true,true,false);
- 无效结果:
yt.www.masthead.sizing.runBeforeBodyIsReady(true,true,true);
我使用了 conn.get_code()
来确认HTTP响应代码总是200。
有没有人知道最近YouTube有没有什么变化可能导致这个问题?
谢谢
1 个回答
0
结果发现问题出在 http://www.youtube.com/results?
这个网址上。
这个网址会被重定向到 https://www.youtube.com/results?
。
如果没有进行重定向,搜索结果就会是“空”的。
我通过 conn.get_url()
验证了这一点:
- 当它返回原始网址(以
http
开头的那个)时,结果是无效的。 - 当它返回重定向后的网址(以
https
开头的那个)时,结果是有效的。