Python3.3提取网页并通过正则表达式来分析

p34f 9年前

      用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*