python正則爬取某段子網站前20頁段子(request庫)過程解析
首先還是谷歌瀏覽器抓包對該網站數據進行分析,結果如下:
該網站地址:http://www.budejie.com/text
該網站數據都是通過html頁面進行展示,網站url默認為第一頁,http://www.budejie.com/text/2為第二頁,以此類推
對網站的內容段子所處位置進行分析,發(fā)現段子內容都是在一個 a 標簽中

坑還是有的,這是我第一次寫的正則:
content_list = re.findall(r'<a href="/detail-.*" rel="external nofollow" rel="external nofollow" rel="external nofollow" >(.+?)</a>', html_str)
之后發(fā)現竟然匹配到了一些推薦的內容,最后我把正則改變下面這樣,發(fā)現沒有問題了,關于正則的知識這里就不做過多解釋了
content_list = re.findall(r'<div class="j-r-list-c-desc">\s*<a href="/detail-.*" rel="external nofollow" rel="external nofollow" rel="external nofollow" >(.+?)</a>', html_str)
現在要的是爬取前20頁的段子并保存到本地,已經知道翻頁的規(guī)律和匹配內容的正則,就直接可以寫代碼了
代碼如下,整體思路還是和前兩排爬蟲博客一樣,面向對象的寫法:
import requests
import re
import json
class NeihanSpider(object):
"""內涵段子,百思不得其姐,正則爬取一頁的數據"""
def __init__(self):
self.temp_url = 'http://www.budejie.com/text/{}' # 網站地址,給頁碼留個可替換的{}
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
}
def pass_url(self, url): # 發(fā)送請求,獲取響應
print(url)
response = requests.get(url, headers=self.headers)
return response.content.decode()
def get_first_page_content_list(self, html_str): # 提取第一頁的數據
content_list = re.findall(r'<div class="j-r-list-c-desc">\s*<a href="/detail-.*" rel="external nofollow" rel="external nofollow" rel="external nofollow" >(.+?)</a>', html_str) # 非貪婪匹配
return content_list
def save_content_list(self, content_list):
with open('neihan.txt', 'a', encoding='utf-8') as f:
for content in content_list:
f.write(json.dumps(content, ensure_ascii=False))
f.write('\n') # 換行
print('成功保存一頁!')
def run(self): # 實現主要邏輯
for i in range(20): # 只爬取前20頁數據
# 1. 構造url
# 2. 發(fā)送請求,獲取響應
html_str = self.pass_url(self.temp_url.format(i+1))
# 3. 提取數據
content_list = self.get_first_page_content_list(html_str)
# 4. 保存
self.save_content_list(content_list)
if __name__ == '__main__':
neihan = NeihanSpider()
neihan.run()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python 實現簡單的shell sed替換功能(實例講解)
下面小編就為大家?guī)硪黄狿ython 實現簡單的shell sed替換功能(實例講解)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
Anaconda+vscode+pytorch環(huán)境搭建過程詳解
這篇文章主要介紹了Anaconda+vscode+pytorch環(huán)境搭建過程詳解,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05

