2016-09-23 127 views
0

我做一個小project.and我想開一家url.i試圖用這種的UnicodeDecodeError:「UTF-8」編解碼器不能在第251位解碼字節0xB5執行:無效的起始字節

url = 'http://www.ygdy8.net/html/gndy/dyzz/index.html' 
content = urllib.request.urlopen(url).read() 

pat = re.compile('<div class="title_all"><h1><front color=#008800>.*?</a>> </front></h1></div>'+ '(.*?)<td height="25" align="center" bgcolor="#F4FAE2"> ',re.S) 
txt = ''.join(pat.findall(content)) 

但是這給我的錯誤

TypeError: can't use a string pattern on a bytes-like object 

然後我試圖與

txt = ''.join(pat.findall(content.decode())) 

但也錯誤

txt = ''.join(pat.findall(content.decode())) 
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb5 in position 251: invalid start byte 

我尋找答案,但我不知道如何解決它。

+0

你試過'content.decode(「latin-1」)嗎? –

+0

我刪除了我的答案。 'latin-1'的作品,但你真的必須得到頭信息知道編碼。鏈接重複問題的答案之一解釋說。 –

+0

標題暗示'content.decode('gb2312',errors ='ignore')'應該可以工作。這就是說,我不認爲你的正則表達式會起作用。 –

回答

0

頭文件暗示content.decode('gb2312',errors ='ignore')應該有效。

>>> content.find(b'charset') 
226 
>>> content[226:226 + 20] 
b'charset=gb2312">\r\n<t' 

但是,你的正則表達式肯定是行不通的。您有front而不是font。也許你想要以下內容:

>>> pat = re.compile(r'<div class="title_all"><h1><font color=#008800>.*?</a>></font></h1></div>'+ r'(.*?)<td height="25" align="center" bgcolor="#F4FAE2"> ',re.S) 

據我所知,這可以捕獲兩件作品之間的表格。

>>> txt = ''.join(pat.findall(content.decode('gb2312',errors='ignore'))) 
>>> print(txt[:500]) 

<div class="co_content8"> 
<ul> 

<td height="220" valign="top"> <table width="100%" border="0" cellspacing="0" cellpadding="0" class="tbspan" style="margin-top:6px"> 
<tr> 
<td height="1" colspan="2" background="/templets/img/dot_hor.gif"></td> 
</tr> 
<tr> 
<td width="5%" height="26" align="center"><img src="/templets/img/item.gif" width="18" height="17"></td> 
<td height="26"> 
    <b> 

     <a href="/html/gndy/dyzz/20160920/52002.html" class="ulink">2016年井柏然楊穎《微微一笑很傾城》HD國語中字</a> 
    </b> 
< 
>>> pat.pattern 
'<div class="title_all"><h1><font color=#008800>.*?</a>></font></h1></div>(.*?)<td height="25" align="center" bgcolor="#F4FAE2"> ' 
>>> 
相關問題