@[TOC]百度飞桨Python小白逆袭大神结营心得
百度飞桨-Python小白逆袭大神-结营心得
很开心参加了这次百度飞桨的python小白逆袭大神的课程,课程内容从Python入手,绝对0基础,老师由浅入深讲解,十分清晰,课程设计也特别有层次感,架构清晰,收获颇丰,总的收获可以概括为以下几点。
一.爬虫
- 任务:完成《青春有你2》选手图片爬取,打印爬取的所有图片的绝对路径,以及爬取的图片总数
- 分析:爬虫的过程,就是模仿浏览器的行为,往目标站点发送请求,接收服务器的响应数据,提取需要的信息,并进行保存的过程。
爬虫过程:发送请求(requests模块);获取响应数据(服务器返回);解析并提取数据(BeautifulSoup查找或者re正则);保存数据
request模块:requests是python实现的简单易用的HTTP库,官网地址:http://cn.python-requests.org/zh_CN/latest/,requests.get(url)可以发送一个http get请求,返回服务器响应内容。
BeautifulSoup库:BeautifulSoup 是一个可以从HTML或XML文件中提取数据的Python库。BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,其中一个是 lxml。 - 实践:
①.爬取百度百科中《青春有你2》中所有参赛选手信息,返回页面数据
import json
import re
import requests
import datetime
from bs4 import BeautifulSoup
import os
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)
soup = BeautifulSoup(response.text,'lxml')
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 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'