最近做計算社會學的研究需要用到網(wǎng)絡爬蟲爬取一些數(shù)據(jù),一開始打算用八爪魚爬蟲工具,后來發(fā)現(xiàn)這種爬蟲工具不太穩(wěn)定,那就自己從頭學吧,以后說不定也能用的著,試著模仿了幾個案例,其實背后的邏輯基本都是一致的,不同網(wǎng)站的結構可能不一樣,不過對付一般的網(wǎng)站是沒什么問題的。
使用的庫:Csv+Request + Beautifulsoup
案例一:爬取豆瓣top250數(shù)據(jù)
要求:抓取top250豆瓣電影的名稱、URL、得分、評價數(shù)。
詳細代碼及注釋如下:
import csv
import re
import requests
from bs4 import BeautifulSoup
要抓取的頁面如下,觀察一下頁面的翻頁規(guī)律

第一頁:https://movie.douban.com/top250?start=0&filter=
第二頁:https://movie.douban.com/top250?start=25&filter=
……
最后一頁:https://movie.douban.com/top250?start=225&filter=
翻頁規(guī)律:只需修改start即可,間隔為25
tips:抓取數(shù)據(jù)時,可以嘗試先抓取一頁的數(shù)據(jù),成功的話加個循環(huán)代碼即可
以第一頁為例,觀察網(wǎng)頁的結構
url = 'https://movie.douban.com/top250?start=0&filter='
response = requests.get(url)
response.encoding = 'utf-8'
html = response.text
soup = BeautifulSoup(html,"lxml") #用beautifulsoup解析網(wǎng)頁
print(soup.prettify()) ## 結構化顯示網(wǎng)頁

觀察可以發(fā)現(xiàn)要抓取的數(shù)據(jù)基本都在<div class="item">類名里
all_list = soup.find_all(class_='item')
tag1 = all_list[0]
item_data = tag1.find(class_='pic')
movie_url = item_data.find('a')['href'] # 抓取電影的url
movie_name = item_data.find('img')['alt'] # 抓取電影的名稱
item_info = tag1.find(class_='star')
info = tag1.find('div', attrs={'class': 'star'}) #通過 find_all() 方法的 attrs 參數(shù)定義一個字典參數(shù)來搜索包含特殊屬性的tag
movie_people =info.find_all('span')[3].get_text()[:-3] # 抓取觀影人數(shù)
movie_score = info.find('span',attrs={'class':'rating_num'}).get_text() #抓取評分
關于beautifulsoup的find() 和find_all()函數(shù),建議參考beautifulsoup的中文文檔:beautifulsoup的中文文檔
會抓一頁的數(shù)據(jù),全部的數(shù)據(jù)自然不在話下
所有代碼如下:
## 用csv模塊創(chuàng)建一個csv文件
with open('C:/Users/Carman/Desktop/top250_movie.csv','w',encoding='utf_8_sig') as outputfile:
writer = csv.writer(outputfile)
outputfile.write("movie_num#movie_name#movie_people#movie_score#movie_url\n") ## 注意縮進,不知道為什么簡書上縮進不了
#開始循環(huán)獲取每一個頁面的url
for list in range(10):
movies_content = requests.get(top250_url.format(list*25))
movies_html = movies_content.encoding = 'utf-8'
soup = BeautifulSoup(movies_html,'html.parser')
all_list = soup.find_all(class_='item')
#在每一個頁面里面循環(huán),抓取名稱、URL、得分、評價數(shù)
for item in all_list:
item_data=item.find(class_='pic')
movie_url = item_data.find('a')['href']
movie_name = item_data.find('img')['alt']
item_info = item.find(class_='star')
info = item.find('div', attrs={'class': 'star'})
movie_people =info.find_all('span')[3].get_text()[:-3]
movie_score = item_info.find('span',attrs={'class':'rating_num'}).get_text()
movie_num = movie_num+1
## 寫入csv文件
outputfile.write('{}#{}#{}#{}#{}\n'.format(movie_num,movie_name,movie_people,movie_score,movie_url))
ok,讀取出來是這個樣子:
import numpy as np
import pandas as pd
df = pd.read_csv('C:/Users/Carman/Desktop/top250_movie.csv',sep='#',encoding='utf-8') #'utf-8'解碼
df.head()

案例2:抓取微博微公益數(shù)據(jù)

如圖,目標在于抓取每個項目的名稱,分類,目標金額,完成率和轉發(fā)數(shù)。
完整代碼如下:
import csv
import re
import requests
from bs4 import BeautifulSoup
import urllib.request as urlrequest
import warnings
warnings.filterwarnings("ignore")
url = 'https://gongyi.weibo.com/list/personal?on_state=3&donate_type=0&state=1&type=0&location=&title=&open=0&page={}'
## 用csv模塊創(chuàng)建一個csv文件
with open('C:/Users/Carman/Desktop/weibo_charity1.csv','w',encoding='utf_8_sig') as outputfile:
writer = csv.writer(outputfile)
outputfile.write("title#kind#organization#target_money#fill_rate#forward\n")
#開始循環(huán)獲取每一個頁面的url
for list in range(1,200):
response = requests.get(url.format(list))
response.encoding = 'utf-8'
html= response.text
soup = BeautifulSoup(html,"lxml")
all_list = soup.find_all(class_ = 'view_info')
#在每一個頁面里面循環(huán),抓取名稱、種類、組織、目標金額、完成率、轉發(fā)
for item in all_list:
title_data = item.find(class_='title')
title = title_data.get_text()[:-6]
kind = title_data.get_text()[-5:-1]
org_data = item.find(class_ ='project_info W_linkb')
organization = org_data.find_all('a')[1].get_text()
num = item.find_all(class_ = 'num')
target_money = num[0].get_text()
fill_rate = num[1].get_text().strip()
forward_people = item.find_all('span')
forward_people = forward_people[2].get_text()
forward_people = forward_people.replace('\t', '')
forward_people = forward_people.replace('\n', '')
## 寫入文件
outputfile.write('{}#{}#{}#{}#{}#{}\n'.format(title,kind,organization,target_money,fill_rate,forward_people))
最后讀取的數(shù)據(jù)格式如下:
import numpy as np
import pandas as pd
data = pd.read_csv('C:/Users/Carman/Desktop/weibo_charity1.csv',sep='#',encoding='utf-8',error_bad_lines=False) #'utf-8'解碼
data.head()

感想:大數(shù)據(jù)時代,現(xiàn)在即使做社科類的研究也越來越需要數(shù)據(jù),對待技術不應該恐懼,這個世界上大部分的事情只要肯去做都是能做好的,另外一項技能學會了一定要找機會經(jīng)常使用,否則過段事件忘了又要重頭在學,有點得不償失了,我經(jīng)常犯這一錯誤,需要引以為戒。