好家伙,爬蟲來了 爬蟲,這玩意,不會怎麼辦, 誒,先抄一份作業回來 1.別人的爬蟲 Python爬蟲史上超詳細講解(零基礎入門,老年人都看的懂)_ChenBinBini的博客-CSDN博客 # -*- codeing = utf-8 -*- from bs4 import BeautifulSoup ...
好家伙,爬蟲來了
爬蟲,這玩意,不會怎麼辦,
誒,先抄一份作業回來
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="(.*?)">') # 創建正則表達式對象,標售規則 影片詳情鏈接的規則
findImgSrc = re.compile(r'<img.*src="(.*?)"', re.S)
findTitle = re.compile(r'<span class="title">(.*)</span>')
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
findJudge = re.compile(r'<span>(\d*)人評價</span>')
findInq = re.compile(r'<span class="inq">(.*)</span>')
findBd = re.compile(r'<p class="">(.*?)</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 = [] # 保存一部電影所有信息
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 = 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="(.*?)">') # 創建正則表達式對象,標售規則 影片詳情鏈接的規則
findImgSrc = re.compile(r'<img.*src="(.*?)"', re.S)
findTitle = re.compile(r'<span class="title">(.*)</span>')
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
findJudge = re.compile(r'<span>(\d*)人評價</span>')
findInq = re.compile(r'<span class="inq">(.*)</span>')
findBd = re.compile(r'<p class="">(.*?)</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="(.*?)"')
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的)
沒什麼難度
這爬了酷狗的一個音樂榜單
然後記錄了一些音樂數據,還有歌曲的地址。
還行,