使用Python編寫爬蟲糗事百科

2021-08-28 10:38:33 字數 3615 閱讀 5538

心血來潮,想爬糗百,剛好在學習python,就拿糗百練練手吧~

先上**,看後再說,嘿嘿嘿。

# _*_  coding:utf-8 _*_

import urllib.request

import re

class qsbk:

# 初始化方法,定義一些變數;

def __init__(self):

# 當前頁碼

self.pageindex = 1

# 模擬瀏覽器的user_agent

# 初始化headers

self.headers =

# 存放每頁段子的列表,每乙個元素是每一頁的段子們

self.stories =

# 儲存資料的檔案

self.file = open("糗事百科.txt", "w", encoding='utf-8')

def __del__(self):

self.file.close()

# 傳入某一頁的索引獲得頁面**

def getpage(self, pageindex):

try:

# url = '' + str(pageindex)

# 構建請求的request

req = urllib.request.request(url, headers=self.headers)

# 利用urlopen獲取頁面**

response = urllib.request.urlopen(req)

# 將頁面轉化為utf-8編碼

pagecode = response.read().decode('utf-8')

return pagecode

except exception as e:

if hasattr(e, "reason"):

print(u"連線糗事百科失敗,錯誤原因:", e.reason)

return none

# 傳入某一頁**,返回本頁不帶的段子列表

def getpageitems(self, pageindex):

pagecode = self.getpage(pageindex)

if not pagecode:

print("頁面載入失敗....")

return none

pattern = re.compile(

'.*?.*?.*?.*?.*?(.*?)(.*?)(.*?)(.*?)',

re.s)

# print pagecode

items = re.findall(pattern, pagecode)

# 用來儲存每頁的段子們

pagestories =

# 遍歷正規表示式匹配的資訊

for item in items:

# 判斷是否已經展示全文

isall = re.search('', item[3])

content = item[2].strip()

if isall is not none:

# 從段子詳情頁獲取完整的段子

url = '' + item[1]

requ = urllib.request.request(url, headers=self.headers)

response = urllib.request.urlopen(requ)

contentcode = response.read().decode('utf-8')

contentpattern = re.compile('(.*?)

', re.s)

content = re.findall(contentpattern, contentcode)[0].strip()

content.replace("\n", "

") # 判斷是否有

imgsrc = re.findall('

if not imgsrc:

# 不包含

# 作者 內容 鏈結 讚數

else:

return pagestories

# 載入並提取頁面的內容,加入到列表中

def loadpage(self):

# 獲取新一頁

pagestories = self.getpageitems(self.pageindex)

# 將該頁的段子存放到全域性list中

if pagestories:

def printstory(self, pagestories, page):

# 遍歷一頁的段子

for story in pagestories:

if story[2] == "":

# 無圖段子

self.file.write(u'\n' % (story[0], story[1]))

print(u"第%d頁\t發布人:%s\n%s\n贊:%s\n" % (page, story[0], story[1], story[3]))

else:

# 有圖段子

self.file.write(

u'\n' % (story[0], story[1], story[2]))

print(u"第%d頁\t發布人:%s\n%s\n:%s\n贊:%s\n" % (page, story[0], story[1], story[2], story[3]))

# 開始方法

def start(self):

print(u"正在讀取糗事百科,請稍後...")

while self.pageindex <= 13:

# 載入內容

self.loadpage()

# 從全域性list中獲取一頁的段子

pagestories = self.stories[0]

# 將全域性list中第乙個元素刪除,因為已經取出

del self.stories[0]

# 輸出該頁的段子

self.printstory(pagestories, self.pageindex)

self.pageindex += 1

else:

print("完畢")

注意:open中的mode 決定了開啟檔案的模式:

咱們這裡用的是寫入許可權

同時建立的「糗事百科.txt」檔案在同一包下,同一目錄中,如圖:

有錯誤請指出,共同進步,共勉!

python爬蟲糗事百科

coding utf 8 import urllib2 import re 工具類 class tools object remove n re.compile r n replace br re.compile r remove ele re.compile r re.s rs 引數,要進行替換的...

Python爬蟲 糗事百科

如果沒有這兩個庫 在命令列任意位置下 前提是你已經配置好了環境,這個網上大把,自行google pip install requests,pip install bs4 import beautifulsoup import requests from bs4 import beautifulsou...

爬蟲 糗事百科爬蟲

糗事百科爬蟲 寫這個爬蟲花了我相當相當多的時間,因為總是爬著爬著就看這糗事百科上的段子去了。環境 python 3.6 import csvimport json import random import requests from bs4 import beautifulsoup class qi...