2017-05-04 64 views

回答

1

错误消息是自我解释的:输入字符串中有一个字节0xf0,该字符串应该是一个ascii字符串。

您应该给出确切的错误消息以及它发生了什么行,但我可以猜到发生在info = urllib.parse.parse_qs(source_code)上,因为parse_qs需要unicode字符串或ascii字节字符串。

第一个问题是,为什么你叫parse_qs数据来自YouTube的到来,因为Python的斯坦达特库的医生说:

Parse a query string given as a string argument (data of type application/x-www-form-urlencoded). Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.

所以你要分析这个对=&性格来解释它作为查询字符串形式key1=value11&key2=value2&key1=value12给予{ 'key1': [ 'value11', 'value12'], 'key2': ['value2']}

如果你知道为什么你想要的,你应该先字节串解码成unicode字符串,使用正确的编码,或者如果不确定Latin1这是能够接受任何字节:

def start(url): 
    source_code = urllib.request.urlopen(url).read().decode('latin1') 
    info = urllib.parse.parse_qs(source_code) 
    print(info) 
1

尝试,因为这.encode一个Unicode对象上工作发生这种

source_code = urllib.request.urlopen(url).read().decode('utf-8') 
+1

感谢你这么很多,它的工作 –

3

错误。因此,我们需要利用

.decode('unicode_escape') 

因此,代码将是字节字符串转换成Unicode字符串:

#!/usr/bin/env python3.5.2 

import urllib.request , urllib.parse 


def start(url): 
    source_code = urllib.request.urlopen(url).read() 
    info = urllib.parse.parse_qs(source_code.decode('unicode_escape')) 
    print(info) 


start('https://www.youtube.com/watch?v=YfRLJQlpMNw') 
+1

谢谢你先生它完美的作品 –

0

此代码是相当奇怪的确实。您正在使用查询解析器来解析网页的内容。 因此,而不是使用parse_qs,你应该使用类似this

相关问题