python爬蟲學習(1)-抓取糗事百科笑話
最近在學習python的爬蟲,參照了http://cuiqingcai.com/990.html的內容,寫了一個爬蟲,抓取流程:傳入引數起始url和輸出檔名稱,使用urllib2對頁面進行抓取,每次抓取一個頁面,迴圈抓取,直到最後一頁。使用正規表示式對抓取到的頁面內容進行提取,並儲存到檔案中。程式如下:
# -*- coding: utf-8
import urllib2
import urllib
import re,os
import time
class Joke:
#初始化資料
def __init__(self,start_url,out_put_file):
self.start_url = start_url
self.out_put_file = out_put_file
self.page = 2
self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
self.headers = { 'User-Agent' : self.user_agent }
#獲取頁面內容的方法
def get_cotent(self,page):
try:
url = self.start_url + str(page) + '/?s=4955352'
request = urllib2.Request(url,headers=self.headers)
response = urllib2.urlopen(request)
act_url = response.geturl()
print 'init url=',url,'act url=',act_url
if url == act_url:
content = response.read()
return content
else:
return None
except urllib2.URLError, e:
if hasattr(e,"reason"):
print u"連線糗事百科失敗,錯誤原因",e.reason
return None
#傳入頁面程式碼,返回笑話內容
def get_joke(self,page):
joke_content = self.get_cotent(page)
str = ''
if not joke_content:
print "抓取完畢"
return None
pattern = re.compile('<div class="author clearfix">.*?<h2>(.*?)</h2>.*?'
+'<div class="content">.*?<span>(.*?)',re.S)
items = re.findall(pattern,joke_content)
for item in items:
str = str + '釋出人:' + item[0] + '\n' + '釋出內容:' + '\n' + item[1] + '\n'+ '\n'
return str
#講抓取到的笑話儲存到檔案的方法
def writeStr2File(self,out_put_file,str1,append = 'a'):
# 去掉檔案,保留路徑。比如 'a/b/c/d.txt' 經過下面程式碼會變成 'a/b/c'
subPath = out_put_file[:out_put_file.rfind('/')]
# 如果給定的路徑中,資料夾不存在,則建立
if not os.path.exists(subPath):
os.makedirs(subPath)
# 開啟檔案並將 str 內容寫入給定的檔案
with open(out_put_file, append) as f:
f.write(str1.strip()+'\n')
#開始抓取頁面內容,每次抓取一個頁面,直到抓取完畢所有頁面
def start_crawl(self):
while True:
joke_str = self.get_joke(self.page)
if not joke_str:
break
time.sleep(1)
#print(joke_str)
self.writeStr2File(self.out_put_file,joke_str)
self.page+=1
spider = Joke('http://www.qiushibaike.com/hot/page/','d:/python/test/out.txt')
spider.start_crawl()
# -*- coding: utf-8
import urllib2
import urllib
import re,os
import time
class Joke:
#初始化資料
def __init__(self,start_url,out_put_file):
self.start_url = start_url
self.out_put_file = out_put_file
self.page = 2
self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
self.headers = { 'User-Agent' : self.user_agent }
#獲取頁面內容的方法
def get_cotent(self,page):
try:
url = self.start_url + str(page) + '/?s=4955352'
request = urllib2.Request(url,headers=self.headers)
response = urllib2.urlopen(request)
act_url = response.geturl()
print 'init url=',url,'act url=',act_url
if url == act_url:
content = response.read()
return content
else:
return None
except urllib2.URLError, e:
if hasattr(e,"reason"):
print u"連線糗事百科失敗,錯誤原因",e.reason
return None
#傳入頁面程式碼,返回笑話內容
def get_joke(self,page):
joke_content = self.get_cotent(page)
str = ''
if not joke_content:
print "抓取完畢"
return None
pattern = re.compile('<div class="author clearfix">.*?<h2>(.*?)</h2>.*?'
+'<div class="content">.*?<span>(.*?)',re.S)
items = re.findall(pattern,joke_content)
for item in items:
str = str + '釋出人:' + item[0] + '\n' + '釋出內容:' + '\n' + item[1] + '\n'+ '\n'
return str
#講抓取到的笑話儲存到檔案的方法
def writeStr2File(self,out_put_file,str1,append = 'a'):
# 去掉檔案,保留路徑。比如 'a/b/c/d.txt' 經過下面程式碼會變成 'a/b/c'
subPath = out_put_file[:out_put_file.rfind('/')]
# 如果給定的路徑中,資料夾不存在,則建立
if not os.path.exists(subPath):
os.makedirs(subPath)
# 開啟檔案並將 str 內容寫入給定的檔案
with open(out_put_file, append) as f:
f.write(str1.strip()+'\n')
#開始抓取頁面內容,每次抓取一個頁面,直到抓取完畢所有頁面
def start_crawl(self):
while True:
joke_str = self.get_joke(self.page)
if not joke_str:
break
time.sleep(1)
#print(joke_str)
self.writeStr2File(self.out_put_file,joke_str)
self.page+=1
spider = Joke('http://www.qiushibaike.com/hot/page/','d:/python/test/out.txt')
spider.start_crawl()
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10972173/viewspace-2133368/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- python爬蟲十二:middlewares的使用,爬取糗事百科Python爬蟲
- python爬取糗事百科Python
- 仿的一個笑話網站 糗事百科網站
- 仿糗事百科笑話系統原始碼,PHP笑話系統原始碼原始碼PHP
- Python爬取糗事百科段子Python
- python爬蟲學習1Python爬蟲
- python多執行緒爬去糗事百科Python執行緒
- 網路爬蟲——專案實戰(爬取糗事百科所有文章)爬蟲
- 【Python學習】爬蟲爬蟲爬蟲爬蟲~Python爬蟲
- python3.6.5 爬取糗事百科,開心一下Python
- Python爬蟲抓取股票資訊Python爬蟲
- selenium爬蟲學習1爬蟲
- python爬蟲是什麼?學習python爬蟲難嗎Python爬蟲
- 用Python爬蟲抓取代理IPPython爬蟲
- Python爬蟲抓取技術的門道Python爬蟲
- 【Python學習筆記1】Python網路爬蟲初體驗Python筆記爬蟲
- 為什麼學習python及爬蟲,Python爬蟲[入門篇]?Python爬蟲
- python爬蟲抓取哈爾濱天氣資訊(靜態爬蟲)Python爬蟲
- 什麼是爬蟲?學習Python爬蟲難不難?爬蟲Python
- python爬蟲—學習筆記-4Python爬蟲筆記
- python爬蟲—學習筆記-2Python爬蟲筆記
- python爬蟲js逆向學習(二)Python爬蟲JS
- Python爬蟲學習筆記(三)Python爬蟲筆記
- python爬蟲學習筆記(二)Python爬蟲筆記
- python爬蟲之抓取小說(逆天邪神)Python爬蟲
- python爬蟲如何爬知乎的話題?Python爬蟲
- 學習C語言還是學習Python爬蟲?C語言Python爬蟲
- Python爬蟲系統化學習(3)Python爬蟲
- Python爬蟲系統化學習(4)Python爬蟲
- Python爬蟲,抓取淘寶商品評論內容!Python爬蟲
- Python爬蟲(1.爬蟲的基本概念)Python爬蟲
- Python爬蟲學習線路圖丨Python爬蟲需要掌握哪些知識點Python爬蟲
- python爬蟲學習01--電子書爬取Python爬蟲
- 一入爬蟲深似海,總結python爬蟲學習筆記!爬蟲Python筆記
- 學習python做爬蟲主要學習哪些內容呢?Python爬蟲
- Python爬蟲之Scrapy學習(基礎篇)Python爬蟲
- Python爬蟲新手教程:手機APP資料抓取 pyspiderPython爬蟲APPIDE
- Python和爬蟲有什麼聯絡?Python學習!Python爬蟲
- 爬蟲原理與資料抓取爬蟲