最近又學了一遍爬蟲的入門,記住步驟立刻就上手了
1.獲取頁面原始碼
5個小步驟:
1.偽裝成瀏覽器
2.進一步包裝請求
3.網頁請求獲取資料
4.解析並儲存
5.返回資料
程式碼:
import urllib.request,urllib.error #指定URL,獲取頁面資料
#爬取指定url
def askUrl(url):
#請求頭偽裝成瀏覽器(字典)
head = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3776.400 QQBrowser/10.6.4212.400"}
#進一步包裝請求
request = urllib.request.Request(url = url,headers=head)
#儲存頁面原始碼
html = ""
try:
#頁面請求,獲取內容
response = urllib.request.urlopen(request)
#讀取返回的內容,用"utf-8"編碼解析
html = response.read().decode("utf-8")
except urllib.error.URLError as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reson"):
print(e.reson)
#返回頁面原始碼
return html
2.獲取標籤
透過BeautifulSoup進一步解析頁面原始碼
from bs4 import BeautifulSoup #頁面解析,獲取資料
Beautiful Soup 將複雜 HTML 文件轉換成一個複雜的樹形結構,每個節點都是 Python 物件,可分為四大物件種類,這裡主要用到Tag類的物件,還有三種,有興趣可以自己去深入學習~~
#構建了一個BeautifulSoup型別的物件soup
#引數為網頁原始碼和”html.parser”,表明是解析html的
bs = BeautifulSoup(html,"html.parser")
#找到所有class叫做item的div,注意class_有個下劃線
bs.find_all('div',class_="item")
3.正則表示式匹配
先準備好相應的正則表示式,然後在上面得到的標籤下手
#Python正則表示式前的 r 表示原生字串(rawstring)
#該字串聲明瞭引號中的內容表示該內容的原始含義,避免了多次轉義造成的反斜槓困擾
#re.S它表示"."的作用擴充套件到整個字串,包括“\n”
#re.compile()編譯後生成Regular Expression物件,由於該物件自己包含了正則表示式
#所以呼叫對應的方法時不用給出正則字串。
#連結
findLink = re.compile(r'<a href="(.*?)">',re.S)
#找到所有匹配的
#引數(正則表示式,內容)
#[0]返回匹配的陣列的第一個元素
link = re.findall(findLink,item)[0]
4.儲存資料
兩種儲存方式
1.儲存到Excel裡
import xlwt #進行excel操作
def saveData(dataList,savePath):
#建立一個工程,引數("編碼","樣式的壓縮效果")
woke = xlwt.Workbook("utf-8",style_compression=0)
#建立一個表,引數("表名","覆蓋原單元格資訊")
sheet = woke.add_sheet("豆瓣電影Top250",cell_overwrite_ok=True)
#列明
col = ("連結","中文名字","英文名字","評分","標題","評分人數","概況")
#遍歷列名,並寫入
for i in range (7):
sheet.write(0,i,col[i])
#開始遍歷資料,並寫入
for i in range (0,250):
for j in range (7):
sheet.write(i+1,j,dataList[i][j])
print("第%d條資料"%(i+1))
#儲存資料到儲存路徑
woke.save(savePath)
print("儲存完畢")
結果檔案:
2.儲存到資料庫
import sqlite3 #進行sql操作
#新建表
def initdb(dataPath):
#連線dataPath資料庫,沒有的話預設新建一個
conn = sqlite3.connect(dataPath)
#獲取遊標
cur = conn.cursor()
#sql語句
sql = '''
create table movie(
id Integer primary key autoincrement,
info_link text,
cname varchar ,
fname varchar ,
rating varchar ,
inq text,
racount varchar ,
inf text
)
'''
#執行sql語句
cur.execute(sql)
#提交事物
conn.commit()
#關閉遊標
cur.close()
#關閉連線
conn.close()
def savedb(dataList,dataPath):
#新建表
initdb(dataPath)
#連線資料庫dataPath
conn = sqlite3.connect(dataPath)
#獲取遊標
cur = conn.cursor()
#開始儲存資料
for data in dataList:
for index in range(len(data)):
#在每個資料欄位兩邊加上""雙引號
data[index] = str('"'+data[index]+'"')
#用","逗號拼接資料
newstr = ",".join(data)
#sql語句,把拼寫好的資料放入sql語句
sql ="insert into movie(info_link,cname,fname,rating,inq,racount,inf)values(%s)"%(newstr)
print(sql)
#執行sql語句
cur.execute(sql)
#提交事務
conn.commit()
#關閉遊標
cur.close()
#關閉連線
conn.close()
print("儲存完畢")
結果檔案:
爬取豆瓣TOP250的所有程式碼
from bs4 import BeautifulSoup #頁面解析,獲取資料
import re #正則表示式
import urllib.request,urllib.error #指定URL,獲取頁面資料
import xlwt #進行excel操作
import sqlite3 #進行sql操作
def main():
baseUrl = "https://movie.douban.com/top250?start="
#1.爬取網頁,並解析資料
dataList = getData(baseUrl)
# savePath=".\\豆瓣電影Top250.xls"
savePath = "movies.db"
#2.儲存資料
# saveData(dateList,savePath)
savedb(dataList,savePath)
#---正則表示式---
#連結
findLink = re.compile(r'<a href="(.*?)">',re.S)
#電影名字
findName = re.compile(r'<span class="title">(.*?)</span>',re.S)
#評分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>')
#標題
findInq = re.compile(r'<span class="inq">(.*?)</span>',re.S)
#評分人數
findCount = re.compile(r'<span>(.*?)人評價</span>')
#電影資訊
findInf = re.compile(r'<p class="">(.*?)</p>',re.S)
#1.爬取網頁
def getData(baseUrl):
dataList = []
for i in range(10):
html = askUrl(baseUrl + str(i * 25))
# 2.逐一解析資料
bs = BeautifulSoup(html,"html.parser")
for item in bs.find_all('div',class_="item"):
data = []
item = str(item)
#連結
link = re.findall(findLink,item)[0]
#名字
name = re.findall(findName,item)
if len(name) == 1:
cName = name[0]
fName = " "
else:
name[1] = name[1].replace(" / ","")
cName = name[0]
fName = name[1]
#評分
rating = re.findall(findRating,item)[0]
#標題
inq = re.findall(findInq,item)
if len(inq) < 1:
inq = " "
else:
inq= inq[0]
#評分人數
racount = re.findall(findCount,item)[0]
#電影資訊
inf = re.findall(findInf,item)[0]
inf = re.sub("...<br(\s+)?/>(\s?)"," ",inf)
inf = re.sub("/"," ",inf)
inf = inf.strip()
#新增一部電影的資訊進data
data.append(link)
data.append(cName)
data.append(fName)
data.append(rating)
data.append(inq)
data.append(racount)
data.append(inf)
dataList.append(data)
return dataList
#爬取指定url
def askUrl(url):
head = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3776.400 QQBrowser/10.6.4212.400"}
request = urllib.request.Request(url = url,headers=head)
http = ""
try:
response = urllib.request.urlopen(request)
http = response.read().decode("utf-8")
except urllib.error.URLError as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reson"):
print(e.reson)
return http
# 3.儲存資料
def saveData(dataList,savePath):
woke = xlwt.Workbook("utf-8",style_compression=0)#樣式的壓縮效果
sheet = woke.add_sheet("豆瓣電影Top250",cell_overwrite_ok=True)#覆蓋原單元格資訊
col = ("連結","中文名字","英文名字","評分","標題","評分人數","概況")
for i in range (7):
sheet.write(0,i,col[i])
for i in range (0,250):
for j in range (7):
sheet.write(i+1,j,dataList[i][j])
print("第%d條資料"%(i+1))
woke.save(savePath)
print("儲存完畢")
#3.儲存到資料庫
def savedb(dataList,dataPath):
initdb(dataPath)
conn = sqlite3.connect(dataPath)
cur = conn.cursor()
#開始儲存資料
for data in dataList:
for index in range(len(data)):
data[index] = str('"'+data[index]+'"')
newstr = ",".join(data)
sql ="insert into movie(info_link,cname,fname,rating,inq,racount,inf)values(%s)"%(newstr)
print(sql)
cur.execute(sql)
conn.commit()
cur.close()
conn.close()
print("儲存完畢")
#3-1新建表
def initdb(dataPath):
conn = sqlite3.connect(dataPath)
cur = conn.cursor()
sql = '''
create table movie(
id Integer primary key autoincrement,
info_link text,
cname varchar ,
fname varchar ,
rating varchar ,
inq text,
racount varchar ,
inf text
)
'''
cur.execute(sql)
conn.commit()
cur.close()
conn.close()
if __name__ == "__main__":
#呼叫函式
main()
愉快爬蟲:
遵守 Robots 協議,但有沒有 Robots 都不代表可以隨便爬,可見下面的大眾點評百度案;
限制你的爬蟲行為,禁止近乎 DDOS的請求頻率,一旦造成伺服器癱瘓,約等於網路攻擊;
對於明顯反爬,或者正常情況不能到達的頁面不能強行突破,否則是 Hacker行為;
最後,審視清楚自己爬的內容,以下是絕不能碰的紅線(包括但不限於): 作者:張凱強
連結:https://www.zhihu.com/question/291554395/answer/514982754
來源:知乎
著作權歸作者所有。
本文章已修改原文用詞符合繁體字使用者習慣使其容易閱讀
版權宣告:此處為CSDN博主「我不是禿頭哆唻咪」的原創文章,依據CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/weixin_44864260/article/details/109558225