溫馨提示×

溫馨提示×

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

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

Python爬蟲實現(xiàn)爬取百度百科詞條功能

發(fā)布時間:2021-06-03 16:26:57 來源:億速云 閱讀:217 作者:Leah 欄目:開發(fā)技術(shù)

Python爬蟲實現(xiàn)爬取百度百科詞條功能?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

爬蟲主程序入口

from crawler_test.html_downloader import UrlDownLoader
from crawler_test.html_outer import HtmlOuter
from crawler_test.html_parser import HtmlParser
from crawler_test.url_manager import UrlManager
# 爬蟲主程序入口
class MainCrawler():
  def __init__(self):
    # 初始值,實例化四大處理器:url管理器,下載器,解析器,輸出器
    self.urls = UrlManager()
    self.downloader = UrlDownLoader()
    self.parser = HtmlParser()
    self.outer = HtmlOuter()
  # 開始爬蟲方法
  def start_craw(self, main_url):
    print('爬蟲開始...')
    count = 1
    self.urls.add_new_url(main_url)
    while self.urls.has_new_url():
      try:
        new_url = self.urls.get_new_url()
        print('爬蟲%d,%s' % (count, new_url))
        html_cont = self.downloader.down_load(new_url)
        new_urls, new_data = self.parser.parse(new_url, html_cont)
        # 將解析出的url放入url管理器,解析出的數(shù)據(jù)放入輸出器中
        self.urls.add_new_urls(new_urls)
        self.outer.conllect_data(new_data)
        if count >= 10:# 控制爬取的數(shù)量
          break
        count += 1
      except:
        print('爬蟲失敗一條')
    self.outer.output()
    print('爬蟲結(jié)束。')
if __name__ == '__main__':
  main_url = 'https://baike.baidu.com/item/Python/407313'
  mc = MainCrawler()
  mc.start_craw(main_url)

URL管理器

# URL管理器
class UrlManager():
  def __init__(self):
    self.new_urls = set() # 待爬取
    self.old_urls = set() # 已爬取
  # 添加一個新的url
  def add_new_url(self, url):
    if url is None:
      return
    elif url not in self.new_urls and url not in self.old_urls:
      self.new_urls.add(url)
  # 批量添加url
  def add_new_urls(self, urls):
    if urls is None or len(urls) == 0:
      return
    else:
      for url in urls:
        self.add_new_url(url)
  # 判斷是否有url
  def has_new_url(self):
    return len(self.new_urls) != 0
  # 從待爬取的集合中獲取一個url
  def get_new_url(self):
    new_url = self.new_urls.pop()
    self.old_urls.add(new_url)
    return new_url

網(wǎng)頁下載器

from urllib import request
# 網(wǎng)頁下載器
class UrlDownLoader():
  def down_load(self, url):
    if url is None:
      return None
    else:
      rt = request.Request(url=url, method='GET')   # 發(fā)GET請求
      with request.urlopen(rt) as rp:         # 打開網(wǎng)頁
        if rp.status != 200:
          return None
        else:
          return rp.read()            # 讀取網(wǎng)頁內(nèi)容

網(wǎng)頁解析器

import re
from urllib import parse
from bs4 import BeautifulSoup
# 網(wǎng)頁解析器,使用BeautifulSoup
class HtmlParser():
  # 每個詞條中,可以有多個超鏈接
  # main_url指url公共部分,如“https://baike.baidu.com/”
  def _get_new_url(self, main_url, soup):
    # baike.baidu.com/
    # <a target="_blank" href="/item/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E8%AF%AD%E8%A8%80" rel="external nofollow" >計算機程序設(shè)計語言</a>
    new_urls = set()
    # 解析出main_url之后的url部分
    child_urls = soup.find_all('a', href=re.compile(r'/item/(\%\w{2})+'))
    for child_url in child_urls:
      new_url = child_url['href']
      # 再拼接成完整的url
      full_url = parse.urljoin(main_url, new_url)
      new_urls.add(full_url)
    return new_urls
  # 每個詞條中,只有一個描述內(nèi)容,解析出數(shù)據(jù)(詞條,內(nèi)容)
  def _get_new_data(self, main_url, soup):
    new_datas = {}
    new_datas['url'] = main_url
    # <dd class="lemmaWgt-lemmaTitle-title"><h2>計算機程序設(shè)計語言</h2>...
    new_datas['title'] = soup.find('dd', class_='lemmaWgt-lemmaTitle-title').find('h2').get_text()
    # class="lemma-summary" label-module="lemmaSummary"...
    new_datas['content'] = soup.find('div', attrs={'label-module': 'lemmaSummary'},
                     class_='lemma-summary').get_text()
    return new_datas
  # 解析出url和數(shù)據(jù)(詞條,內(nèi)容)
  def parse(self, main_url, html_cont):
    if main_url is None or html_cont is None:
      return
    soup = BeautifulSoup(html_cont, 'lxml', from_encoding='utf-8')
    new_url = self._get_new_url(main_url, soup)
    new_data = self._get_new_data(main_url, soup)
    return new_url, new_data

輸出處理器

# 輸出器
class HtmlOuter():
  def __init__(self):
    self.datas = []
  # 先收集數(shù)據(jù)
  def conllect_data(self, data):
    if data is None:
      return
    self.datas.append(data)
    return self.datas
  # 輸出為HTML
  def output(self, file='output_html.html'):
    with open(file, 'w', encoding='utf-8') as fh:
      fh.write('<html>')
      fh.write('<head>')
      fh.write('<meta charset="utf-8"></meta>')
      fh.write('<title>爬蟲數(shù)據(jù)結(jié)果</title>')
      fh.write('</head>')
      fh.write('<body>')
      fh.write(
        '<table >')
      fh.write('<tr>')
      fh.write('<th >URL</th>')
      fh.write('<th >詞條</th>')
      fh.write('<th >內(nèi)容</th>')
      fh.write('</tr>')
      for data in self.datas:
        fh.write('<tr>')
        fh.write('<td >{0}</td>'.format(data['url']))
        fh.write('<td >{0}</td>'.format(data['title']))
        fh.write('<td >{0}</td>'.format(data['content']))
        fh.write('</tr>')
      fh.write('</table>')
      fh.write('</body>')
      fh.write('</html>')

效果(部分):

Python爬蟲實現(xiàn)爬取百度百科詞條功能

看完上述內(nèi)容,你們掌握Python爬蟲實現(xiàn)爬取百度百科詞條功能的方法了嗎?如果還想學到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(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