項目內容:
用Python寫的糗事百科的網絡爬蟲。
使用方法:
新建一個Bug.py文件,然后將代碼復制到里面后,雙擊運行。
程序功能:
在命令提示行中瀏覽糗事百科。
原理解釋:
首先,先瀏覽一下糗事百科的主頁:http://www.qiushibaike.com/hot/page/1
可以看出來,鏈接中page/后面的數字就是對應的頁碼,記住這一點為以后的編寫做準備。
然后,右擊查看頁面源碼:
觀察發現,每一個段子都用div標記,其中class必為content,title是發帖時間,我們只需要用正則表達式將其“扣”出來就可以了。
明白了原理之后,剩下的就是正則表達式的內容了,可以參照這篇文章:
//www.jb51.net/article/57150.htm
運行效果:
代碼如下:
# -*- coding: utf-8 -*-
import urllib2
import urllib
import re
import thread
import time
#----------- 加載處理糗事百科 -----------
class Spider_Model:
def __init__(self):
self.page = 1
self.pages = []
self.enable = False
# 將所有的段子都扣出來,添加到列表中并且返回列表
def GetPage(self,page):
myUrl = "http://m.qiushibaike.com/hot/page/" + page
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
req = urllib2.Request(myUrl, headers = headers)
myResponse = urllib2.urlopen(req)
myPage = myResponse.read()
#encode的作用是將unicode編碼轉換成其他編碼的字符串
#decode的作用是將其他編碼的字符串轉換成unicode編碼
unicodePage = myPage.decode("utf-8")
新聞熱點
疑難解答