python 百度百科 爬虫_爬虫爬取百度百科数据
以前段時間《青春有你2》為例,我們使用Python來爬取百度百科中《青春有你2》所有參賽選手的信息。
什么是爬蟲?
為了獲取大量的互聯網數據,我們自然想到使用爬蟲代替我們完成這些重復的工作。
爬蟲的過程,就是模仿瀏覽器的行為,往目標站點發送請求,接收服務器的響應數據,提取需要的信息,并進行保存的過程。
Python為爬蟲的實現提供了工具:requests模塊、BeautifulSoup庫
接下來我們就會使用這些工具來獲取我們想要的信息。
任務描述
本次實踐使用Python來爬取百度百科中《青春有你2》所有參賽選手的信息。
上網的全過程
普通用戶:
打開瀏覽器 --> 往目標站點發送請求 --> 接收響應數據 --> 渲染到頁面上。
爬蟲程序:
模擬瀏覽器 --> 往目標站點發送請求 --> 接收響應數據 --> 提取有用的數據 --> 保存到本地/數據庫。
爬蟲的過程
1.發送請求(requests模塊)
2.獲取響應數據(服務器返回)
3.解析并提取數據(BeautifulSoup查找或者re正則)
4.保存數據
模塊簡介
request模塊
requests.get(url)可以發送一個http get請求,返回服務器響應內容。
BeautifulSoup庫
BeautifulSoup支持Python標準庫中的HTML解析器,還支持一些第三方的解析器,其中一個是 lxml。
BeautifulSoup(markup, "html.parser")或者BeautifulSoup(markup, "lxml"),推薦使用lxml作為解析器,因為效率更高。
第一步
具體來說,這一步是爬取百度百科中《青春有你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)
#將一段文檔傳入BeautifulSoup的構造方法,就能得到一個文檔的對象, 可以傳入一段字符串
soup = BeautifulSoup(response.text,'lxml')
#返回的是class為table-view log-set-param的
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)
第三步
爬取每個選手的圖片,并進行保存。
這一步我們就可以獲得所有小姐姐的美照了。一共下載482張照片。
具體的思路是從上一步得到的個人信息中進入每個人的百度百科,然后再進入相冊,下載照片并保存。
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']
response = requests.get(link,headers=headers)
bs = BeautifulSoup(response.text,'lxml')
pic_list_url = bs.select('.summary-pic a')[0].get('href')
pic_list_url = 'https://baike.baidu.com' + pic_list_url
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("所有信息爬取完成!")
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python 百度百科 爬虫_爬虫爬取百度百科数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: E24- please install
- 下一篇: windows下安装mysql 开机启动