今天爬蟲(新浪微博 個人信息頁面)的時候遇到了轉義和正則匹配中文出亂碼的問題。
先給出要匹配的部分網頁源代碼如下:
<span class=\"pt_title S_txt2\">昵稱:<\/span><span class=\"pt_detail\">他們叫我遠凸哥哥<\/span><\/li>\r\n\t\t
想要匹配得到的結果是這個人的昵稱,即“他們叫我遠凸哥哥”
1.轉義
比較簡單,需要轉義的是反斜杠(\)和引號(")
1 >>> content='<span class=\\\"pt_title S_txt2\\\">昵稱:<\\/span><span class=\\\"pt_detail\\\">他們叫我遠凸哥哥<\\/span><\\/li>\\r\\n\\t\\t' 2 >>> print content 3 <span class=\"pt_title S_txt2\">昵稱:<\/span><span class=\"pt_detail\">他們叫我遠凸哥哥<\/span><\/li>\r\n\t\t
2. 匹配中文亂碼的問題
問題如下:
1 >>> re.findall(r'(?<=昵稱:<\\/span><span class=\\\"pt_detail\\\">).*?(?=<\\/span>)',content) 2 ['\xcb\xfb\xc3\xc7\xbd\xd0\xce\xd2\xd4\xb6\xcd\xb9\xb8\xe7\xb8\xe7']
百度和google了一下,知道了大概思路就是要decode('utf8')。有說pattern要寫成u'pattern'的,不過我試了好像沒什么用,不知道是不是我用的2.X版本。最后解決辦法如下:
1 #! /usr/bin/env python 2 #coding=utf8 3 4 import re 5 content6='<span class=\\\"pt_title S_txt2\\\">昵稱:<\\/span><span class=\\\"pt_detail\\\">他們叫我遠凸哥哥<\\/span><\\/li>\\r\\n\\t\\t' 6 b=re.findall(r'(?<=昵稱:<\\/span><span class=\\\"pt_detail\\\">).*?(?=<\\/span>)',content6) 7 print b[0].decode('utf8') 8 他們叫我遠凸哥哥
不知道大家有什么更好的寫法,網上的寫法試了好幾種,我這里都是不行的。