爬蟲小程序

#爬蟲小程序#

我們爬取豆瓣如下圖所示的top250電影

爬蟲小程序

我們的爬蟲程序可以獲取電影的名稱,評分和推薦語。爬取出來的數據存在excel表格裡面如下圖

爬蟲小程序

用python寫爬蟲程序

#導入爬蟲需要的庫
import requests #requests獲取網頁的庫
import openpyxl #openpyxl存儲數據的庫
from bs4 import BeautifulSoup #BeautifulSoup 解析網頁

wb = openpyxl.Workbook() #創建工作窗口
sheet = wb.active #激活一個sheet
sheet.title = '豆瓣爬蟲' #命名sheet的名字
sheet['A1'] ='電影名稱' #加表頭,給A1單元格賦值
sheet['B1'] ='電影評分' #加表頭,給B1單元格賦值
sheet['C1'] ='推薦語 ' #加表頭,給C1單元格賦值

for x in range(10):
url = 'https://movie.douban.com/top250?start=' + str(25*x) + '&filter=' #網頁
res = requests.get(url) #獲取網頁
soup = BeautifulSoup(res.text,'html.parser') #用BeautifulSoup解析網頁

items = soup.find('ol',class_='grid_view').find_all('li') #爬取網頁
try: #因為在爬取數據時會因為某些電影沒有推薦語而報錯,所以用try的方法嘗試爬取,如果沒有數據則跳過,不會報錯
for item in items:
name = item.find('div',class_='hd').find('span',class_='title').text
score = item.find('span',class_='rating_num').text
words = item.find(class_='quote').find('span',class_='inq').text
print(name,score,words)
sheet.append([name,score,words])
except:
pass
wb.save('豆瓣爬蟲.xlsx') #保存excel文件

這樣我們的爬蟲程序就完成了,感興趣的話可以私信我拿爬蟲的代碼,或者在我的github上面下載https://github.com/1428409697/pachong,明天我將結合周志華機器學習發表一篇神經網絡的正向和逆向傳遞的原理以及公式的推導,有興趣的朋友可以關注我。


分享到:


相關文章: