python爬蟲如何批量爬取糗事百科段子
問題描述
剛學Python不會scrapy框架,就是想做個簡單爬蟲實現抓取前10頁段子(前N頁)。請問不用scrapy能有什么簡單一些的代碼能實現?之前有試過在page那里加for循環,但是也只能抓到一個頁面,不知道怎么弄。
import urllibimport urllib2import repage = 1url = ’http://www.qiushibaike.com/8hr/page/’ + str(page)user_agent = ’Mozilla/5.0 ( Windows NT 6.1)’headers = { ’User-Agent’ : user_agent }try: request = urllib2.Request(url,headers = headers) response = urllib2.urlopen(request) content = response.read().decode(’utf-8’) pattern = re.compile(’<p.*?class='content'>.*?<span>(.*?)</span>.*?</p>.*?’,re.S) items = re.findall(pattern,content) for item in items:print itemexcept urllib2.URLError, e: if hasattr(e,'code'):print e.code if hasattr(e,'reason'):print e.reason
問題解答
回答1:我跑了一下你的代碼,發現能跑出前2個頁面,后面都返回了一個錯誤碼,我覺得是因為你沒做防反爬處理,因為你這個結果在一秒內就跑出來了,一秒內連續10次訪問肯定不是人能做到的。
很多網站都能知道你這是用代碼在刷他們的網站,有些網站很討厭這個,會做反爬處理,可能直接把你的 IP 都給封了,讓你沒法訪問,因為如果不這樣做,短時間內直接訪問太多次的話可能會把人家的網站都弄癱瘓了。
我的建議是每爬完一個頁面等待1秒,修改了下你的代碼:
import urllibimport urllib2import reimport timefor page in range(1, 11): print(’at page %s’ % page) url = ’http://www.qiushibaike.com/8hr/page/’ + str(page) user_agent = ’Mozilla/5.0 ( Windows NT 6.1)’ headers = { ’User-Agent’ : user_agent } try:request = urllib2.Request(url,headers = headers)response = urllib2.urlopen(request)content = response.read().decode(’utf-8’)pattern = re.compile(’<p.*?class='content'>.*?<span>(.*?)</span>.*?</p>.*?’,re.S)items = re.findall(pattern,content)for item in items: print item except urllib2.URLError, e:if hasattr(e,'code'): print e.codeif hasattr(e,'reason'): print e.reasontime.sleep(1)
我這邊是能出結果的,不過我想向你推薦另一個第三方的庫,叫 requests,既然你會 urllib,這也就不難,但是使用起來更人性化,配合 BeatuifulSoup 庫(用來解析和處理 HTML 文本的)很方便,你也可以去網上搜一下,了解一下。
還有就是以后做爬蟲一定要注意做防反爬處理!
相關文章:
1. Java反射問題:為什么android.os.Message的recycleUnchecked方法不能通過反射獲取到?2. 如何分別在Windows下用Winform項模板+C#,在MacOSX下用Cocos Application項目模板+Objective-C實現一個制作游戲的空的黑窗口?3. html5和Flash對抗是什么情況?4. php如何獲取訪問者路由器的mac地址5. javascript - 在 vue里面用import引入js文件,結果為undefined6. 前端 - node vue webpack項目文件結構7. 小程序怎么加外鏈,語句怎么寫!求救新手,開文檔沒發現8. python - linux怎么在每天的凌晨2點執行一次這個log.py文件9. javascript - vue-resource中如何設置全局的timeout?10. thinkPHP5中獲取數據庫數據后默認選中下拉框的值,傳遞到后臺消失不見。有圖有代碼,希望有人幫忙
