溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用python正則爬取某段子網(wǎng)站前20頁段子

發(fā)布時間:2021-08-21 14:44:17 來源:億速云 閱讀:216 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹如何使用python正則爬取某段子網(wǎng)站前20頁段子,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

首先還是谷歌瀏覽器抓包對該網(wǎng)站數(shù)據(jù)進行分析,結(jié)果如下:

該網(wǎng)站地址:http://www.budejie.com/text

該網(wǎng)站數(shù)據(jù)都是通過html頁面進行展示,網(wǎng)站url默認為第一頁,http://www.budejie.com/text/2為第二頁,以此類推

對網(wǎng)站的內(nèi)容段子所處位置進行分析,發(fā)現(xiàn)段子內(nèi)容都是在一個 a 標簽中

如何使用python正則爬取某段子網(wǎng)站前20頁段子

坑還是有的,這是我第一次寫的正則:

content_list = re.findall(r'<a href="/detail-.*" rel="external nofollow" rel="external nofollow" rel="external nofollow" >(.+?)</a>', html_str)

之后發(fā)現(xiàn)竟然匹配到了一些推薦的內(nèi)容,最后我把正則改變下面這樣,發(fā)現(xiàn)沒有問題了,關(guān)于正則的知識這里就不做過多解釋了

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)

現(xiàn)在要的是爬取前20頁的段子并保存到本地,已經(jīng)知道翻頁的規(guī)律和匹配內(nèi)容的正則,就直接可以寫代碼了

代碼如下,整體思路還是和前兩排爬蟲博客一樣,面向?qū)ο蟮膶懛ǎ?/strong>

import requests
import re
import json

class NeihanSpider(object):
  """內(nèi)涵段子,百思不得其姐,正則爬取一頁的數(shù)據(jù)"""
  def __init__(self):
    self.temp_url = 'http://www.budejie.com/text/{}' # 網(wǎng)站地址,給頁碼留個可替換的{}
    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ā)送請求,獲取響應(yīng)
    print(url)
    response = requests.get(url, headers=self.headers)
    return response.content.decode()

  def get_first_page_content_list(self, html_str): # 提取第一頁的數(shù)據(jù)
    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): # 實現(xiàn)主要邏輯
    for i in range(20): # 只爬取前20頁數(shù)據(jù)
      # 1. 構(gòu)造url
      # 2. 發(fā)送請求,獲取響應(yīng)
      html_str = self.pass_url(self.temp_url.format(i+1))
      # 3. 提取數(shù)據(jù)
      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正則爬取某段子網(wǎng)站前20頁段子”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI