日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python 百度百科 爬虫_爬虫爬取百度百科数据

發(fā)布時(shí)間:2023/12/19 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 百度百科 爬虫_爬虫爬取百度百科数据 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

以前段時(shí)間《青春有你2》為例,我們使用Python來爬取百度百科中《青春有你2》所有參賽選手的信息。

什么是爬蟲?

為了獲取大量的互聯(lián)網(wǎng)數(shù)據(jù),我們自然想到使用爬蟲代替我們完成這些重復(fù)的工作。

爬蟲的過程,就是模仿瀏覽器的行為,往目標(biāo)站點(diǎn)發(fā)送請(qǐng)求,接收服務(wù)器的響應(yīng)數(shù)據(jù),提取需要的信息,并進(jìn)行保存的過程。

Python為爬蟲的實(shí)現(xiàn)提供了工具:requests模塊、BeautifulSoup庫

接下來我們就會(huì)使用這些工具來獲取我們想要的信息。

任務(wù)描述

本次實(shí)踐使用Python來爬取百度百科中《青春有你2》所有參賽選手的信息。

上網(wǎng)的全過程

普通用戶:

打開瀏覽器 --> 往目標(biāo)站點(diǎn)發(fā)送請(qǐng)求 --> 接收響應(yīng)數(shù)據(jù) --> 渲染到頁面上。

爬蟲程序:

模擬瀏覽器 --> 往目標(biāo)站點(diǎn)發(fā)送請(qǐng)求 --> 接收響應(yīng)數(shù)據(jù) --> 提取有用的數(shù)據(jù) --> 保存到本地/數(shù)據(jù)庫。

爬蟲的過程

1.發(fā)送請(qǐng)求(requests模塊)

2.獲取響應(yīng)數(shù)據(jù)(服務(wù)器返回)

3.解析并提取數(shù)據(jù)(BeautifulSoup查找或者re正則)

4.保存數(shù)據(jù)

模塊簡(jiǎn)介

request模塊

requests.get(url)可以發(fā)送一個(gè)http get請(qǐng)求,返回服務(wù)器響應(yīng)內(nèi)容。

BeautifulSoup庫

BeautifulSoup支持Python標(biāo)準(zhǔn)庫中的HTML解析器,還支持一些第三方的解析器,其中一個(gè)是 lxml。

BeautifulSoup(markup, "html.parser")或者BeautifulSoup(markup, "lxml"),推薦使用lxml作為解析器,因?yàn)樾矢摺?/p>

第一步

具體來說,這一步是爬取百度百科中《青春有你2》中所有參賽選手信息,返回頁面數(shù)據(jù)

也就是將如圖的多有參賽學(xué)員信息爬取并返回。

import json

import re

import requests

import datetime

from bs4 import BeautifulSoup

import os

#獲取當(dāng)天的日期,并進(jìn)行格式化,用于后面文件命名,格式: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的構(gòu)造方法,就能得到一個(gè)文檔的對(duì)象, 可以傳入一段字符串

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 = "參賽學(xué)員"

for table in tables:

#對(duì)當(dāng)前節(jié)點(diǎn)前面的標(biāo)簽和字符串進(jìn)行查找

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)

第二步

對(duì)爬取的頁面數(shù)據(jù)進(jìn)行解析,并保存為JSON文件。

那么我們?cè)谶@一步就可以獲得如圖所有人的具體信息了~~

def parse_wiki_data(table_html):

'''從百度百科返回的html中解析得到選手信息,以當(dāng)前日期作為文件名,存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

#個(gè)人百度百科鏈接

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

#花語,去除掉花語中的單引號(hào)或雙引號(hào)

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)

第三步

爬取每個(gè)選手的圖片,并進(jìn)行保存。

這一步我們就可以獲得所有小姐姐的美照了。一共下載482張照片。

具體的思路是從上一步得到的個(gè)人信息中進(jìn)入每個(gè)人的百度百科,然后再進(jìn)入相冊(cè),下載照片并保存。

def crawl_pic_urls():

'''爬取每個(gè)選手的百度百科圖片,并保存'''

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)

#根據(jù)圖片鏈接列表pic_urls, 下載所有圖片,保存在以name命名的文件夾中

down_pic(name,pic_urls)

def down_pic(name,pic_urls):

'''根據(jù)圖片鏈接列表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張圖片時(shí)失敗:%s' % (str(i + 1), str(pic_url)))

print(e)

continue

第四步

打印爬取的所有圖片的路徑

def show_pic_path(path):

'''遍歷所爬取的每張圖片,并打印所有圖片的絕對(duì)路徑'''

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)

#從每個(gè)選手的百度百科頁面上爬取圖片,并保存

crawl_pic_urls()

#打印所爬取的選手圖片路徑

show_pic_path('/home/aistudio/work/pics/')

print("所有信息爬取完成!")

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

以上是生活随笔為你收集整理的python 百度百科 爬虫_爬虫爬取百度百科数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。