作業說明:
1、使用Python來爬取百度百科中《青春有你2》所有參賽選手的信息,完成《青春有你2》選手圖片爬取,將爬取圖片進行保存
數據獲取
2、打印爬取的所有圖片的絕對路徑,以及爬取的圖片總數
實現效果:
思路:
首先,瞭解一下 深度學習一般過程:
其次,瞭解一下 爬蟲的過程:
1.發送請求(requests模塊)
2.獲取響應數據(服務器返回)
3.解析並提取數據(BeautifulSoup查找或者re正則)
4.保存數據
另外,瞭解一下 兩個模塊:
1、request模塊:
requests是python實現的簡單易用的HTTP庫
官網地址:http://cn.python-requests.org/zh_CN/latest/
requests.get(url)可以發送一個http get請求,返回服務器響應內容。
2、BeautifulSoup庫:
BeautifulSoup 是一個可以從HTML或XML文件中提取數據的Python庫。
網址:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
BeautifulSoup支持Python標準庫中的HTML解析器, 還支持一些第三方的解析器, 其中一個是 lxml。
BeautifulSoup(markup, “html.parser”)或者BeautifulSoup(markup, “lxml”),推薦使用lxml作爲解析器,因爲效率更高。
開始編程爬取:
準備工作:
#如果需要進行持久化安裝, 需要使用持久化路徑, 如下方代碼示例:
#!mkdir /home/aistudio/external-libraries
#!pip install beautifulsoup4 -t /home/aistudio/external-libraries
#!pip install lxml -t /home/aistudio/external-libraries
# 同時添加如下代碼, 這樣每次環境(kernel)啓動的時候只要運行下方代碼即可:
import sys
sys.path.append('/home/aistudio/external-libraries')
GO:
一、爬取百度百科中《青春有你2》中所有參賽選手信息,返回頁面數據
import json
import re
import requests
import datetime
from bs4 import BeautifulSoup
import os
#獲取當天的日期,並進行格式化,用於後面文件命名,格式:20200420
today = datetime.date.today().strftime('%Y%m%d')
def crawl_wiki_data():
"""
爬取百度百科中《青春有你2》中參賽選手信息,返回html
"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
url='https://baike.baidu.com/item/青春有你第二季'
try:
response = requests.get(url,headers=headers)
print(response.status_code)
#將一段文檔傳入BeautifulSoup的構造方法,就能得到一個文檔的對象, 可以傳入一段字符串
soup = BeautifulSoup(response.text,'lxml')
#返回的是class爲table-view log-set-param的<table>所有標籤
tables = soup.find_all('table',{'class':'table-view log-set-param'})
crawl_table_title = "參賽學員"
for table in tables:
#對當前節點前面的標籤和字符串進行查找
table_titles = table.find_previous('div').find_all('h3')
for title in table_titles:
if(crawl_table_title in title):
return table
except Exception as e:
print(e)
二、對爬取的頁面數據進行解析,並保存爲JSON文件
def parse_wiki_data(table_html):
'''
從百度百科返回的html中解析得到選手信息,以當前日期作爲文件名,存JSON文件,保存到work目錄下
'''
bs = BeautifulSoup(str(table_html),'lxml')
all_trs = bs.find_all('tr')
error_list = ['\'','\"']
stars = []
for tr in all_trs[1:]:
all_tds = tr.find_all('td')
star = {}
#姓名
star["name"]=all_tds[0].text
#個人百度百科鏈接
star["link"]= 'https://baike.baidu.com' + all_tds[0].find('a').get('href')
#籍貫
star["zone"]=all_tds[1].text
#星座
star["constellation"]=all_tds[2].text
#身高
star["height"]=all_tds[3].text
#體重
star["weight"]= all_tds[4].text
#花語,去除掉花語中的單引號或雙引號
flower_word = all_tds[5].text
for c in flower_word:
if c in error_list:
flower_word=flower_word.replace(c,'')
star["flower_word"]=flower_word
#公司
if not all_tds[6].find('a') is None:
star["company"]= all_tds[6].find('a').text
else:
star["company"]= all_tds[6].text
stars.append(star)
json_data = json.loads(str(stars).replace("\'","\""))
with open('work/' + today + '.json', 'w', encoding='UTF-8') as f:
json.dump(json_data, f, ensure_ascii=False)
三、爬取每個選手的百度百科圖片,並進行保存
def crawl_pic_urls():
'''
爬取每個選手的百度百科圖片,並保存
'''
with open('work/'+ today + '.json', 'r', encoding='UTF-8') as file:
json_array = json.loads(file.read())
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
for star in json_array:
name = star['name']
link = star['link']
#!!!請在以下完成對每個選手圖片的爬取,將所有圖片url存儲在一個列表pic_urls中!!!
# pic_urls = [] # 新建列表每次循環初始化
# r = requests.get(link, headers=headers) # 獲取每個頁面的信息
# # print(r.text)
# soup = BeautifulSoup(r.text, 'lxml') # 解析頁面
# # print(soup)
# migs = soup.find_all('div', class_='summary-pic')
# # print(migs)
# migs = migs[0].a.get('href') # 獲取鏈接的部分內容
# if 'http' not in migs: # 避免其他內容干擾報錯
# # print(migs)
# url = f'http://baike.baidu.com{migs}' # 拼接鏈接
# # print(url)
# photo_r = requests.get(url, headers=headers) # 獲取鏈接頁面
# # print(photo_r.text)
# pic_urls.append(photo_r)
#向選手個人百度百科發送一個http get請求
response=requests.get(link, headers=headers)
# 將一段文檔傳入BeautifulSoup的構造方法,就能得到一個文檔的對象
bs=BeautifulSoup(response.text, 'lxml')
# 從百度百科頁面解析得到一個鏈接,該鏈接指向選手圖片列表頁面
pic_list_url=bs.select('.summary-pic a')[0].get('href')
pic_list_url='http://baike.baidu.com' + pic_list_url
# 想選手圖片列表頁面發送http get請求
pic_list_response=requests.get(pic_list_url, headers=headers)
# 對選手圖片列表頁面進行解析,獲取所有圖片鏈接
bs=BeautifulSoup(pic_list_response.text, 'lxml')
pic_list_html=bs.select('.pic-list img')
pic_urls=[]
for pic_html in pic_list_html:
pic_url=pic_html.get('src')
pic_urls.append(pic_url)
#!!!根據圖片鏈接列表pic_urls, 下載所有圖片,保存在以name命名的文件夾中!!!
down_pic(name,pic_urls)
def down_pic(name,pic_urls):
'''
根據圖片鏈接列表pic_urls, 下載所有圖片,保存在以name命名的文件夾中,
'''
path = 'work/'+'pics/'+name+'/'
if not os.path.exists(path):
os.makedirs(path)
for i, pic_url in enumerate(pic_urls):
try:
pic = requests.get(pic_url, timeout=15)
string = str(i + 1) + '.jpg'
with open(path+string, 'wb') as f:
f.write(pic.content)
print('成功下載第%s張圖片: %s' % (str(i + 1), str(pic_url)))
except Exception as e:
print('下載第%s張圖片時失敗: %s' % (str(i + 1), str(pic_url)))
print(e)
continue
四、打印爬取的所有圖片的路徑
def show_pic_path(path):
'''
遍歷所爬取的每張圖片,並打印所有圖片的絕對路徑
'''
pic_num = 0
for (dirpath,dirnames,filenames) in os.walk(path):
for filename in filenames:
pic_num += 1
print("第%d張照片:%s" % (pic_num,os.path.join(dirpath,filename)))
print("共爬取《青春有你2》選手的%d照片" % pic_num)
if __name__ == '__main__':
#爬取百度百科中《青春有你2》中參賽選手信息,返回html
html = crawl_wiki_data()
#解析html,得到選手信息,保存爲json文件
parse_wiki_data(html)
#從每個選手的百度百科頁面上爬取圖片,並保存
crawl_pic_urls()
#打印所爬取的選手圖片路徑
show_pic_path('/home/aistudio/work/pics/')
print("所有信息爬取完成!")
至此,爬取成功!
♥ 喜 歡 請 點 贊 喲 ♥ |
(●ˇ∀ˇ●) |