Python例項 網路爬蟲抓取豆瓣3萬本書(4)

2021-07-28 16:19:27 字數 4334 閱讀 6110

新的知識點:

1.re模組,正規表示式

表示式中的分組:

組是通過 "(" 和 ")" 元字元來標識的。 "(" 和 ")" 有很多在數學表示式中相同的意思;它們一起把在它們裡面的表示式組成一組。

2.time模組,日期和時間相關的模組

每個時間戳都以自從2023年1月1日 00:00:00過了多長時間來表示。

詳細內容:

3.urllib模組,處理url相關的東西

4.os.path.isfile檢測的是路徑

os.listdir返回的是字串list。

如果直接用這個字串去isfile的時候,一般是回報錯的。

isfile檢測的位置是當前位置,即是'.'。所以要把rootdir加進去。

for path in os.listdir(rootdir):

if os.path.isfile(os.path.join(rootdir,path)) and path.endswith(prefix):

print(path)

5.string.format()使用很方便。

insertbooksql = "insert into `book` 

(`bookname`, `bookurl`, `bookimg`, `bookinfo`, `bookstar`, `bookno`) 

values ('" \"', '', '', '', '', '')"

insert1 = insertbooksql.format(

bookname=bookname, 

bookurl=bookurl, 

bookimg=bookimage, 

bookinfo=bookinfo, 

bookstar=bookstar, bookno=bookno)

第四步是將各個標籤的書列表抓取到本地。

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

import time

from tool.excelmanager import listfiles,readexcel

from tool.proxymanager import makeproxyaddress

import urllib.parse

import os

from tool.htmlmanager import gethtml,getbinaryhtml

import re

# 抓取各標籤列表頁

""" 輸入引數為:

requireip 是否使用**,預設否

v 是否限制爬蟲速度,預設否,時間為1秒仿人工

lockprefix 檔案加鎖字尾

"""requreip = 0

lockprefix= 'html'

v = 2

# 進行計時

starttime = time.clock() #開始時間

taglist = readexcel('web/booktag.xlsx') # 從excel檔案中讀取標籤列表。返回序列

proxyaddress = makeproxyaddress()# **ip陣列

changeip = 0 # **ip陣列

# 迴圈對標籤進行抓取

for i in range( 1, len( taglist ) ):

tagtype = taglist[i][0] # 大分類

tagname = taglist[i][1] # 標籤名

tag = urllib.parse.quote(tagname) # url中文轉碼

localdir = 'web/'+tagtype

# 先構建目錄,已經存在就不需要

if os.path.exists(localdir):

pass

else:# 否則新建

print('新建大分類:'+localdir)

os.makedirs(localdir)

mulu = localdir+'/'+tagname

# 存在標籤資料夾則跳過

if os.path.exists(mulu):

pass

else: # 否則新建方便網頁存放

print('新建標籤資料夾'+mulu)

os.makedirs(mulu)

# 網路中斷後重新抓取時判斷是否加鎖

ok = listfiles(mulu, '.'+lockprefix)

if ok:

print('類別:'+tagtype+'----標籤:'+tagname+'----已經抓完') # 抓完

continue

url = ''+tag+'/book?start=' # 基礎**

pagesize = 15 # 每頁15本

i = 0 # 翻頁助手

while(true):

# 需要爬取的網頁

site = url+str(i*pagesize)

# 開始爬取

# 構造檔名稱

# web/**/0.html

src = mulu+'/'+str(i*15)+'.html'

# 判斷檔案是否存在,存在則不抓取節省時間

if(os.path.exists(src) == true):

pass

else:

# 寫入本地檔案

print('準備抓取:【'+site+'】 類別:【'+tagtype+'】 標籤:【'+tagname+'】')

iprefuse = 1 # 如果抓取成功設為0

# 如果抓取出錯那重新抓取

while iprefuse:

try:

daili1= proxyaddress[changeip] # **ip

# 爬蟲速度控制

if v:

a = time.clock()#初試時間

time.sleep(v)

b = time.clock()

print('時間暫停:'+str(v))

print('真實時間暫停(unix cpu時間,windows 真實時間):'+str(b-a))

# 不需要**

if requreip==0:

# 獲得**內容

webcontent = gethtml(site).encode('utf-8') # 爬取

#搜尋是否出現dl標籤

notnull = re.search(r'',webcontent.decode('utf-8','ignore')) # 匹配看是否抓取到末頁

else: # 需要**

print('**:'+daili1)

webcontent = getbinaryhtml(site, daili1)

# 獲取**內容

notnull = re.search(r'',webcontent.decode('utf-8','ignore'))

iprefuse = 0# 抓完設定0

except exception as e:#抓取過程中出錯。

print(e)

if requreip:#換乙個ip試試

changeip = changeip+1 # 更換ip下標

if changeip==len(proxyaddress): # 到達ip陣列末迴圈再來

changeip = 0

print('更換**:'+proxyaddress[changeip])

else:

print("ip被封")

raise

# break

# 如果抓不到標籤,證明已經抓取完

if notnull:

webfile = open(src, 'wb')#儲存網頁到本地

webfile.write(webcontent)

webfile.close()

print("已經抓取:"+site+'類別:'+tagtype+'----標籤:'+tagname)

else:

lock = open(src.replace('html',lockprefix),'w') # 抓取完畢了

# 日期:

finish = time.strftime("%y-%m-%d %h:%m:%s", time.localtime())

print("抓取完畢:"+tagname)

break

i =i + 1 # 加頁

# 計時

endtime = time.clock()

print("爬取總共執行時間 : %.03f 秒" %(endtime-starttime))

Python 網路爬蟲抓取有道詞典

content input 請輸入需要翻譯的內容 輸入 e 退出程式 if content e break url 有道詞典的請求 head 設定乙個頭部使得瀏覽器認為不是用python進行訪問 head user agent mozilla 5.0 windows nt 10.0 win64 x6...

Python網路爬蟲之抓取訂餐資訊

本文以大眾點評網為例,獲取頁面的餐館資訊,以達到練習使用python的目的。import urllib.request import re def fetchfood url 模擬使用瀏覽器瀏覽大眾點評的方式瀏覽大眾點評 headers user agent opener urllib.reques...

python 爬蟲 基本抓取

首先,python中自帶urllib及urllib2這兩個模組,基本上能滿足一般的頁面抓取,另外,requests 也是非常有用的。對於帶有查詢欄位的url,get請求一般會將來請求的資料附在url之後,以?分割url和傳輸資料,多個引數用 連線。data requests data為dict,js...