好家伙,爬蟲來了
爬蟲,這玩意,不會怎么辦,
誒,先抄一份作業回來
1.別人的爬蟲
Python爬蟲史上超詳細講解(零基礎入門,老年人都看的懂)_ChenBinBini的博客-CSDN博客
# -*- codeing = utf-8 -*-
from bs4 import BeautifulSoup # 網頁決議,獲取資料
import re # 正則運算式,進行文字匹配`
import urllib.request, urllib.error # 制定URL,獲取網頁資料
import xlwt # 進行excel操作
#import sqlite3 # 進行SQLite資料庫操作
findLink = re.compile(r'<a href="https://www.cnblogs.com/FatTiger4399/p/(.*?)">') # 創建正則運算式物件,標售規則 影片詳情鏈接的規則
findImgSrc = https://www.cnblogs.com/FatTiger4399/p/re.compile(r'<img.*src="https://www.cnblogs.com/FatTiger4399/p/(.*?)"', re.S)
findTitle = re.compile(r'<span >(.*)</span>')
findRating = re.compile(r'<span property="v:average">(.*)</span>')
findJudge = re.compile(r'<span>(\d*)人評價</span>')
findInq = re.compile(r'<span >(.*)</span>')
findBd = re.compile(r'<p >(.*?)</p>', re.S)
def main():
baseurl = "https://movie.douban.com/top250?start=" #要爬取的網頁鏈接
# 1.爬取網頁
datalist = getData(baseurl)
savepath = "豆瓣電影Top250.xls" #當前目錄新建XLS,存盤進去
# dbpath = "movie.db" #當前目錄新建資料庫,存盤進去
# 3.保存資料
saveData(datalist,savepath) #2種存盤方式可以只選擇一種
# saveData2DB(datalist,dbpath)
# 爬取網頁
def getData(baseurl):
datalist = [] #用來存盤爬取的網頁資訊
for i in range(0, 10): # 呼叫獲取頁面資訊的函式,10次
url = baseurl + str(i * 25)
html = askURL(url) # 保存獲取到的網頁原始碼
# 2.逐一決議資料
soup = BeautifulSoup(html, "html.parser")
for item in soup.find_all('div', class_="item"): # 查找符合要求的字串
data = https://www.cnblogs.com/FatTiger4399/p/[] # 保存一部電影所有資訊
item = str(item)
link = re.findall(findLink, item)[0] # 通過正則運算式查找
data.append(link)
imgSrc = re.findall(findImgSrc, item)[0]
data.append(imgSrc)
titles = re.findall(findTitle, item)
if (len(titles) == 2):
ctitle = titles[0]
data.append(ctitle)
otitle = titles[1].replace("/", "") #消除轉義字符
data.append(otitle)
else:
data.append(titles[0])
data.append(' ')
rating = re.findall(findRating, item)[0]
data.append(rating)
judgeNum = re.findall(findJudge, item)[0]
data.append(judgeNum)
inq = re.findall(findInq, item)
if len(inq) != 0:
inq = inq[0].replace(",", "")
data.append(inq)
else:
data.append(" ")
bd = re.findall(findBd, item)[0]
bd = re.sub('<br(\s+)?/>(\s+)?', "", bd)
bd = re.sub('/', "", bd)
data.append(bd.strip())
datalist.append(data)
return datalist
# 得到指定一個URL的網頁內容
def askURL(url):
head = { # 模擬瀏覽器頭部資訊,向豆瓣服務器發送訊息
"User-Agent": "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 80.0.3987.122 Safari / 537.36"
}
# 用戶代理,表示告訴豆瓣服務器,我們是什么型別的機器、瀏覽器(本質上是告訴瀏覽器,我們可以接收什么水平的檔案內容)
request = urllib.request.Request(url, headers=head)
html = ""
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
return html
# 保存資料到表格
def saveData(datalist,savepath):
print("save.......")
book = xlwt.Workbook(encoding="utf-8",style_compression=0) #創建workbook物件
sheet = book.add_sheet('豆瓣電影Top250', cell_overwrite_ok=True) #創建作業表
col = ("電影詳情鏈接","圖片鏈接","影片中文名","影片外國名","評分","評價數","概況","相關資訊")
for i in range(0,8):
sheet.write(0,i,col[i]) #列名
for i in range(0,250):
# print("第%d條" %(i+1)) #輸出陳述句,用來測驗
data =https://www.cnblogs.com/FatTiger4399/p/ datalist[i]
for j in range(0,8):
sheet.write(i+1,j,data[j]) #資料
book.save(savepath) #保存
if __name__ == "__main__": # 當程式執行時
# 呼叫函式
main()
# init_db("movietest.db")
print("爬取完畢!")

臥槽,有點東西
這東西看上去挺nb啊,
也很方便,把我想要的一些資料直接總結到一個excel表格中了
我們來看看這些欄位是如何匹配的
.xls

代碼:
findLink = re.compile(r'<a href="https://www.cnblogs.com/FatTiger4399/p/(.*?)">') # 創建正則運算式物件,標售規則 影片詳情鏈接的規則
findImgSrc = https://www.cnblogs.com/FatTiger4399/p/re.compile(r'<img.*src="https://www.cnblogs.com/FatTiger4399/p/(.*?)"', re.S)
findTitle = re.compile(r'<span >(.*)</span>')
findRating = re.compile(r'<span property="v:average">(.*)</span>')
findJudge = re.compile(r'<span>(\d*)人評價</span>')
findInq = re.compile(r'<span >(.*)</span>')
findBd = re.compile(r'<p >(.*?)</p>', re.S)
<img>?<span>? 這不就專業對口了嗎
網站的html:

將三個"表"都打開,再來看看對比

(誒都對上了)
此處,使用正則運算式去匹配對應標簽
正則運算式 – 簡介 | 菜鳥教程 (runoob.com)
于是看了這個案例之后,我們就可以大概去分析以下爬蟲到底干了什么:
1.發請求,隨后拿到服務器發過來的.html檔案
2.用正則運算式去套對應的,我們需要的資料
3.處理資料,最后把他們以某種方式呈現
具體來說,爬蟲通常會執行以下步驟:
-
發送HTTP請求:爬蟲通過發送HTTP請求來獲取目標網頁的內容,
-
決議HTML頁面:網頁內容一般是HTML格式的,爬蟲需要使用HTML決議器來將頁面內容決議成Python物件,
-
提取資料:通過Python編程語言對決議出來的物件進行遍歷和操作,找到需要的資料并保存下來,
-
存盤資料:將提取的資料保存到檔案中、資料庫中或者記憶體中,以備后續的處理和分析,
-
處理例外:爬蟲需要處理例外,例如:請求超時、決議錯誤等,以確保爬蟲的穩定性和可靠性,
開干
2.我的爬蟲
好了,我們自己寫一個爬蟲試試
import requests
from bs4 import BeautifulSoup
import xlwt
import re
# 創建Excel檔案
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('kugou_rank')
# pattern = re.compile(r'(?<=- ).*')
# 構造請求頭
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
# 定義排行榜頁面的URL
url = 'https://www.kugou.com/yy/rank/home/1-6666.html?from=rank'
# 發送請求并獲取回應
r = requests.get(url, headers=headers)
# 決議HTML
soup = BeautifulSoup(r.text, 'html.parser')
# 定位歌曲排行榜串列
song_list = soup.find('div', {'class': 'pc_temp_songlist'}).find_all('li')
# 將資料寫入Excel檔案
worksheet.write(0, 0, '排名') #寫入對應的欄位
worksheet.write(0, 1, '歌名')
worksheet.write(0, 2, '歌手')
worksheet.write(0, 3, '專輯')
worksheet.write(0, 4, '播放時長')
worksheet.write(0, 5, '鏈接地址')
row = 1
for song in song_list:
song_name = song.find('a', {'class': 'pc_temp_songname'}).text.strip() #篩選出歌名
song_title = song.get('title')
singer_pattern = re.compile(r'.*(?= - )')
song_singer = singer_pattern.findall(song_title)
song_title = song.get('title')
print(song_title)
album_pattern = re.compile(r'(?<=- ).*')
song_album = album_pattern.findall(song_title)
# song_album = pattern.findall(song)
song_time = song.find('span', {'class': 'pc_temp_time'}).text.strip()
link_pattern = re.compile(r'href="https://www.cnblogs.com/FatTiger4399/p/(.*?)"')
worksheet.write(row, 0, song['data-index']) #將排行寫入excel表格
worksheet.write(row, 1, song_name) #將歌名寫入excel表格
worksheet.write(row, 2, song_singer) #將歌手寫入excel表格
worksheet.write(row, 3, song_album) #將歌曲專輯寫入excel表格
worksheet.write(row, 4, song_time) #將歌曲時長寫入excel表格
song =str(song)
song = song.split("javascript:")[0]
song_link = link_pattern.findall(song)
worksheet.write(row, 5, song_link) #將歌曲時長寫入excel表格
row += 1
# 保存Excel檔案
workbook.save('C:/Users/10722/Desktop/python答辯/kugou_rank.xls')
說明:
# 構造請求頭
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
帶著請求頭去請求,一個簡單的"反爬"機制,模仿瀏覽器去發請求,非常實用
(其實沒什么亂用,你能想到的,網站的開發者大概也能想到,所以你要是亂來還是會封你IP的)
沒什么難度
這爬了酷狗的一個音樂榜單
然后記錄了一些音樂資料,還有歌曲的地址,

還行,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/555435.html
標籤:Python
下一篇:返回列表
