最近又學了一遍爬蟲的入門,記住步驟立刻就上手了
爬蟲四大步驟
- 1.獲取頁面源代碼
- 2.獲取標簽
- 3.正則運算式匹配
- 4.保存資料
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
來源:知乎
著作權歸作者所有,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/210107.html
標籤:python
上一篇:python學習: 用random、time和pyplot函式制作一段簡單的代碼
下一篇:C語言復習上
