我用Python抓取了7000 多本電子書案例詳解

這篇文章主要介紹了我用Python抓取了7000 多本電子書案例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

安裝

安裝很簡單,只要執行:

pip install requests-html

就可以了。

分析頁面結構

通過瀏覽器審查元素可以發現這個電子書網站是用 WordPress 搭建的,首頁列表元素很簡單,很規整

所以我們可以查找 .entry-title > a 獲取所有圖書詳情頁的鏈接,接着我們進入詳情頁,來尋找下載鏈接,由下圖

可以發現 .download-links > a 裏的鏈接就是該書的下載鏈接,回到列表頁可以發現該站一共 700 多頁,由此我們便可以循環列表獲取所有的下載鏈接。

Requests-html 快速指南

發送一個 GET 請求:

from requests_html import HTMLSession
session = HTMLSession()
 
r = session.get('https://python.org/')

Requests-html 的方便之處就是它解析 html 方式就像使用 jQuery 一樣簡單,比如:

# 獲取頁面的所有鏈接可以這樣寫:
r.html.links
# 會返回 {'//docs.python.org/3/tutorial/', '/about/apps/'}
 
# 獲取頁面的所有的絕對鏈接:
r.html.absolute_links
# 會返回 {'https://github.com/python/pythondotorg/issues', 'https://docs.python.org/3/tutorial/'}
 
# 通過 CSS 選擇器選擇元素:
about = r.find('.about', first=True)
# 參數 first 表示只獲取找到的第一元素
about.text # 獲取 .about 下的所有文本
about.attrs # 獲取 .about 下所有屬性像 id, src, href 等等
about.html # 獲取 .about 的 HTML
about.find('a') # 獲取 .about 下的所有 a 標籤

構建代碼

from requests_html import HTMLSession
import requests
import time
import json
import random
import sys
 
'''
想要學習Python?Python學習交流羣:984632579滿足你的需求,資料都已經上傳羣文件,可以自行下載!
'''
 
session = HTMLSession()
list_url = 'http://www.allitebooks.com/page/'
 
USER_AGENTS = [
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
  "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
  "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
  "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
  "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
  "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
  "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
  "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
  "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
  "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
  "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10"
]
 
# 獲取當前列表頁所有圖書鏈接
def get_list(url):
  response = session.get(url)
  all_link = response.html.find('.entry-title a') # 獲取頁面所有圖書詳情鏈接
  for link in all_link:
    getBookUrl(link.attrs['href'])
 
# 獲取圖書下載鏈接
def getBookUrl(url):
  response = session.get(url)
  l = response.html.find('.download-links a', first=True)
  if l is not None: # 運行後發現有的個別頁面沒有下載鏈接,這裏加個判斷
    link = l.attrs['href'];
    download(link)
 
#下載圖書
def download(url):
  # 隨機瀏覽器 User-Agent
  headers={ "User-Agent":random.choice(USER_AGENTS) }
  # 獲取文件名
  filename = url.split('/')[-1]
  # 如果 url 裏包含 .pdf
  if ".pdf" in url:
    file = 'book/'+filename # 文件路徑寫死了,運行時當前目錄必須有名 book 的文件夾
    with open(file, 'wb') as f:
      print("正在下載 %s" % filename)
      response = requests.get(url, stream=True, headers=headers)
      
      # 獲取文件大小
      total_length = response.headers.get('content-length')
      # 如果文件大小不存在,則直接寫入返回的文本
      if total_length is None: 
        f.write(response.content)
      else:
        # 下載進度條
        dl = 0
        total_length = int(total_length) # 文件大小
        for data in response.iter_content(chunk_size=4096): # 每次響應獲取 4096 字節
          dl += len(data)
          f.write(data)
          done = int(50 * dl / total_length)
          sys.stdout.write("\r[%s%s]" % ('=' * done, ' ' * (50-done)) ) # 打印進度條  
          sys.stdout.flush()
 
      print(filename + '下載完成!')
 
if __name__ == '__main__':
  #從這運行,應爲知道列表總數,所以偷個懶直接開始循環
  for x in range(1,756):
    print('當前頁面: '+ str(x))
    get_list(list_url+str(x))

運行效果:

以上所述是小編給大家介紹的我用Python抓取了7000 多本電子書案例詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對神馬文庫網站的支持!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章