Python3.3提取網頁并通過正則表達式來分析

p34f 9年前發布 | 51K 次閱讀 Python3 Python開發

      用Python3.3來訪問頁面。并解析出內容是爬蟲程序設計的基礎,下面就是個例子,函數GetURL用于取得一個頁面的源數據。在函數中,python模擬一個瀏覽器的訪問。取得結果可能會包括非unicode的編碼。下面方面教大家怎么查編碼

      在IE瀏覽器中打開要訪問的頁面,在頁中按鼠標右鍵。選擇編碼。可以查看當前的編碼是什么。

      Python3.3提取網頁并通過正則表達式來分析
      通過request.open打開的是一個bytes數組,直接通過調用decode來完成轉換。轉換后,就成了unicode字符串。

      ParseURL則是采用正則表達式來提取有用的信息。本例子中是用來提取“東方財富網”中某股票的資金流動情況。

#URL
import sys
import re
import urllib.request as request

#codec can be 'gb2312','utf8' etc
def getCode(strText,codec):
   b = bytes((ord(i) for i in strText))  
   return b.decode(codec)



def GetURL(strURL):
   headers = ('User-Agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11')
   opener = request.build_opener()
   opener.addheaders = [headers]
   response = opener.open(strURL).read()
   #print(type(response))
   return response.decode("gb2312")

def ParseURL(strResp):
   pattern = re.compile(r"
\s*\s*\s*\s*\s*\s*\s*\s*\s*\s*\s*\s*")
   match = pattern.findall(strResp)
   if match:
       for result in match:
           for item in result:
               print(item,end=" ")
           print()


xxx = GetURL(r"http://data.eastmoney.com/zjlx/600030.html")
ParseURL(xxx)
#print(xxx)
\s*(\d*-\d*-\d*)\s* \s*([+.\-0-9]+).*\s*    \s*([+.\-0-9]+).*\s*    \s*([+.\-0-9]+).*\s*    \s*([+.\-0-9]+).*\s*    \s*([+.\-0-9]+).*\s*    \s*([+.\-0-9]+).*\s*    \s*([+.\-0-9]+).*\s*    \s*([+.\-0-9]+).*\s*    \s*([+.\-0-9]+).*\s*    \s*([+.\-0-9]+).*\s*    \s*([+.\-0-9]+).*\s*    \s*([+.\-0-9]+).*\s*
 


 本文由用戶 p34f 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!