零基础入门python爬虫之《青春有你2》选手信息爬取
零基础入门python爬虫之《青春有你2》选手信息爬取
完成《青春有你2》选手图片爬取,生成选手图片的绝对路径并输出,统计爬取的图片总数量。使用工具:requests模块、BeautifulSoup库。文末附课程总体代码,操作平台为AI Studio
爬虫步骤分解:
1)了解网页:青春有你2(《青春有你2》网址);
2)requests库抓取网站数据;
3)BeautifulSoup解析网页;
4)清洗和组织数据;
1. 了解网页
进入《青春有你2》网站首页,使用快捷键【Ctrl+U】方式或者【右键】->【检查】打开源码页面。
【Ctrl+F】可调用搜索框实现快速定位。
网页结构
网页一般由三部分组成,分别是 HTML(超文本标记语言)、CSS(层叠样式表)和 JScript(活动脚本语言)。
HTML
HTML 是整个网页的结构,相当于整个网站的框架。带“<”、“>”符号的都是属于 HTML 的标签,并且标签都是成对出现的。
常见的标签如下:
<html>..</html> 表示标记中间的元素是网页 <body>..</body> 表示用户可见的内容 <div>..</div> 表示框架 <p>..</p> 表示段落 <li>..</li>表示列表 <img>..</img>表示图片 <h1>..</h1>表示标题 <a href="">..</a>表示超链接 <table>..<table>表示表格 <tr>..<tr>表示行 <td>..<td>表示单元格
CSS
CSS 表示样式,定义了外观。
JScript
JScript表示功能。交互的内容和各种特效都在 JScript 中,JScript 描述了网站中的各种功能。
如果用人体来比喻,HTML 是人的骨架,并且定义了人的嘴巴、眼睛、耳朵等要长在哪里。CSS 是人的外观细节,如嘴巴长什么样子,眼睛是双眼皮还是单眼皮,是大眼睛还是小眼睛,皮肤是黑色的还是白色的等。JScript 表示人的技能,例如跳舞、唱歌或者演奏乐器等。
2、requests库
requests是python实现的简单易用的HTTP库,官网地址:http://cn.python-requests.org/zh_CN/latest/
网页请求的过程分为两个环节:requests(请求)、response(相应)。
网页请求的方式也分为两种:
(1)GET:最常见的方式,一般用于获取或者查询资源信息,也是大多数网站使用的方式,响应速度快。
(2)POST:相比 GET 方式,多了以表单形式上传参数的功能,因此除查询信息外,还可以修改信息。
代码解析
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' }#解决requests请求反爬方式之一,伪装成网页的服务器本身来爬取数据 url='https://baike.baidu.com/item/青春有你第二季'
requests.get(url)发送http get请求,返回内容response为URL对象,表示整个网页。
response = requests.get(url,headers=headers) print(response.status_code) #响应状态码,200表示成功
提取网页中的源码:
response.text
BeautifulSoup解析网页
Beautiful Soup 是解析HTML和XML的工具,并提取的数据。包含
html.parser、
lxml等多种解析器
#将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串 soup = BeautifulSoup(response.text,'lxml')#把html变量采用‘lxml’解析器进行解析 #返回的是class为table-view log-set-param的<table>所有标签 tables = soup.find_all('table',{'class':'table-view log-set-param'})#搜索对应内容为下图所示
find_all()用于搜索当前节点下所有的符合条件的节点
没有指点节点则是全文
find_all(name, attrs, recursive, text, **kwargs)
name:节点的标签名,查找所有名为name的节点(tag对象)
attrs:查询含有属性值的标签
text:查询接收的文本标签,是字符串形式
**kwargs:接收常用的属性通过赋值的形式表达
find()返回查询到的第一个元素节点,与
find_all()略有不同
整体代码
#如果需要进行持久化安装, 需要使用持久化路径, 如下方代码示例: # !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') #一、爬取百度百科中《青春有你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) #响应状态码,200表示成功# print(response.text) #将一段文档传入BeautifulSoup的构造方法,就能得到一个文档的对象, 可以传入一段字符串 soup = BeautifulSoup(response.text,'lxml') #返回的是class为table-view log-set-param的<table>所有标签 tables = soup.find_all('table',{'class':'table-view log-set-param'}) # print(tables) 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): # print(table) 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') # print(all_trs) error_list = ['\'','\"'] stars = [] for tr in all_trs[1:]: all_tds = tr.find_all('td') # print(all_tds) star = {} #姓名 star["name"]=all_tds[0].t ext #个人百度百科链接 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中!!! 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基础有了很大的提高,在课程中边学习边运用,而且循序渐进,逐步提高,课程安排也非常适合小白入门,从前四次作业的基础累计,到最后大作业的完成,每一步的学习都为最后的应用打下了基础,全程都有助教答疑,在交流群里可以与随时提问,学习氛围浓厚,特别喜欢人美心善的文老师,授课内容非常详细,简直太爱了,真的收获很多,当完成大作业时满满的成就感,非常期待下一期的论文复现营。
酱紫, 原创文章 3获赞 1访问量 309 关注 私信调试平台为:AI Studio,
代码来源为:七日打卡营之作业二https://aistudio.baidu.com/aistudio/education/group/info/1224
参考内容:
https://blog.csdn.net/weixin_45623093/article/details/105628483
http://c.biancheng.net/view/2011.html
- [置顶] python爬虫实践——零基础快速入门(四)爬取小猪租房信息
- Python爬虫入门2 | 爬取豆瓣电影信息
- Python爬虫入门二之爬虫基础了解
- [置顶] python爬虫实践——零基础快速入门(二)爬取豆瓣电影
- python爬虫学习,零基础入门(一)
- 利用爬虫对《青春有你2》选手信息爬取
- 个人随手自学笔记--python3入门及基础知识点(5)—— 枚举、闭包、表达式、函数、装饰器、小爬虫
- 小白学 Python 爬虫(3):前置准备(二)Linux基础入门
- Python爬虫入门(2):爬虫基础了解
- Python基础学习-爬虫入门知识
- python爬虫入门(二) HTML基础
- Python爬虫开发(一):零基础入门
- python3爬虫之入门基础和正则表达式
- 2019最新全套七月Python基础入门+进阶熟练班+ 数据分析班+爬虫项目
- python爬虫入门——爬取淘宝商品评论信息
- python爬虫入门(1) 基础知识 ; 正则表达式 Re 模块
- 转 Python爬虫入门二之爬虫基础了解
- python爬虫零基础入门
- python3爬虫入门基础
- Python爬虫入门二之爬虫基础了解