2006年10月28日 星期六 17:03
现在百度的mp3搜索不能直接点击下载了,需要点击链接打开新窗口再下载,这样网上以前的一些百度mp3下载工具和python代码
都失效了,找了一下还没有找到当前依然可用的程序,就打算写一个,基本上完成了。
谈一下到目前为止的感受,程序内部使用UTF-8编码处理GBK数据真痛苦,尤其是处理URL和html内容。就拿这个下载mp3的小爬
虫为例,参看下面的一断代码。所提交的查询URL中的中文关键字对搜索结果有直接影响,虽然已经把URL转换成了gbk编码再提
交,但是获取的搜索结果却不能使用gbk编码来解码,大概是因为结果中有个别的UTF-8编码的字符?
def GetSongURLs(artist, title):
"""Search results in baidu can't be downloaded directly,
this function get top 30(or less) urls from the results.
arguments:
artist: artist
title: title/song name
return values:
urls: urls got from search results.
"""
baseurl = '
http://mp3.baidu.com/m?f=ms&tn;=baidump3&ct;=134217728&lf;=&rn;=&lm;=0&word;='
keyword = '%s %s' %(artist, title)
keyword = keyword.decode('utf8').encode('gbk') #这里,已经把关键字转为gbk编码了
url = baseurl + urllib.quote(keyword, string.punctuation)
html = urllib2.urlopen(url).read()
try:
html = html.decode('gbk').encode('utf8') # 但是这里有时候解码会出错
except UnicodeDecodeError:
print url #打印出解码会出错的页面的url,在浏览器中打开没看出有什么不正常
sys.exit(1)
pattern = 'http://.*baidusg.*&lm;=16777216'
urls = re.findall(pattern, html)
if len(urls) >= 10:
return urls[:10]
else:
return urls
上面代码中我用红色所注释的地方有时候会解码失败, 但是也不是完全不能用,相反是绝大多数情况下都很正常,但
就是在某些为知的情况下会失败。
编码转来转去觉得很头疼,最终还是妥协了,程序内部使用gbk,不再转来转去了,sigh……
还有就是以前也遇到过,有一些文本,无论尝试用什么编码都无法解码,是因为这些文本中含有不止一种编码的字符?不知道处理这类问题有没有什么好的方法。
--
I like Python & Linux.
Blog: http://recordus.cublog.cn
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://python.cn/pipermail/python-chinese/attachments/20061028/b262db22/attachment.htm
2006年10月28日 星期六 17:09
试试 html.decode('gbk' , 'ignore') 看
--
http://codeplayer.blogspot.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://python.cn/pipermail/python-chinese/attachments/20061028/3f6f332c/attachment.html
2006年10月28日 星期六 17:15
另外建议出错时检查一下服务器返回的http头,也许对寻找报错的原因有所帮助。
2006年10月28日 星期六 17:19
2006/10/28, yi huang <yi.codeplayer at gmail.com>: > > 试试 html.decode('gbk' , 'ignore') 看 > 试了一下,这个方法很有效,又学了一招,呵呵,回头再仔细看看decode和encode。 -- I like Python & Linux. Blog: http://recordus.cublog.cn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://python.cn/pipermail/python-chinese/attachments/20061028/f1b5589a/attachment.htm
2006年10月28日 星期六 17:22
2006/10/28, Elias Soong <elias.soong at gmail.com>: > > 另外建议出错时检查一下服务器返回的http头,也许对寻找报错的原因有所帮助。 > 你指的是这个吗?比如: conn = urllib.urlopen('http://www.google.com') info = conn.info() info.headers #是这个吗? -- I like Python & Linux. Blog: http://recordus.cublog.cn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://python.cn/pipermail/python-chinese/attachments/20061028/7f981a60/attachment.html
2006年10月29日 星期日 15:27
> 你指的是这个吗?比如:
> conn = urllib.urlopen('http://www.google.com')
> info = conn.info()
> info.headers #是这个吗?
我是这个意思。从中应该能看出HTTP服务器的一些设置信息,考虑到大的网站应该会大量应用集群技术,所以不同访问期间可能会涉及到不同的服务器,也许其中设置会稍有差别。所以在出错的时候不妨把这些信息也记录下来。不过是否和报错的原因有关就只能说是我的猜想了。
Zeuux © 2025
京ICP备05028076号