爬虫实战:嗅事百科段子多页爬取
生活随笔
收集整理的這篇文章主要介紹了
爬虫实战:嗅事百科段子多页爬取
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
假如我們想爬取糗事百科( http://ww qiushibaike.com/)上的段子,也可以編寫對應的Python網絡爬蟲實現。
本項目糗事百科網絡爬蟲的實現思路及步驟如下:
定義正則表達式
用戶
審查元素
查看源代碼
多審查幾個用戶,
于是我們可以定義規則
userpat=str('<h2>(.*?)</h2>')內容
于是可以定義內容正則
全部代碼
import urllib.request import re from urllib import request def getcontent(url,page):headers = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3947.100 Safari/537.36")opener = urllib.request.build_opener()opener.addheaders = [headers]# 將opener安裝為全局urllib.request.install_opener(opener)url_request = request.Request(url)html1 = request.urlopen(url_request, timeout=10)data=html1.read().decode('utf-8')#構建用戶正則表達式userpat=str('<h2>(.*?)</h2>')#構建內容正則表達式contentpat = '<div class="content">(.*?)</div>'#尋找出所有用戶userlist=re.compile(userpat,re.S).findall(data)#尋找所有的內容contentlist=re.compile(contentpat,re.S).findall(data)x=1#通過for循環遍歷段子內容并將內容賦值給對應的變量for content in contentlist:content=content.replace('\n','')#用字符串作為變量名,先將對應的字符串賦值給一個變量name="content"+str(x)exec(name+'=content')x+=1y=1#通過for循環遍歷用戶,并始終輸出 該用戶對應的內容for user in userlist:name='content'+str(y)print('用戶'+str(page)+str(y)+'是:'+user)print('內容是:')exec("print("+name+")")print('\n')y+=1for i in range(10):url='https://www.qiushibaike.com/text/page/'+str(i)+'/'getcontent(url,i)函數解析
exec()是一個十分有趣且使用的內置函數,不同于eval()函數只能執行計算數學表達式的結果的功能,exec()能夠動態地執行復雜的Python代碼,能夠十分強大
首先是一個簡單的小例子,代碼如下:
答案·156
總結
以上是生活随笔為你收集整理的爬虫实战:嗅事百科段子多页爬取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 日料是什么?
- 下一篇: python 多线程讲解(如何实现多线程