week04day03(爬虫 beautifulsoup4、)

一. 使用bs4解析网页

python 复制代码
'''
下载bs4 - pip install beautifulsoup4
使用的时候 import bs4

专门用于解析网页的第三方库
在使用bs4的时候往往会依赖另一个库lxml
pip install lxml
'''

网页代码

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Title</title>
	</head>
	<body>
		<h2>电影大全</h2>
		<div id="box1">
			<div class="item">
				<p>肖生克的救赎</p>
				<span>评分:</span>
				<span class="score">9.7</span>
			</div>
			<div class="item">
				<p>霸王别姬</p>
				<span>评分:</span>
				<span class="score">9.6</span>
			</div>
			<div class="item">
				<p>阿甘正传</p>
				<span>评分:</span>
				<span class="score">9.5</span>
			</div>
			<img src="https://img9.doubanio.com/view/photo/s_ratio_poster/public/p457760035.webp" class="">
			<div id="box2">
				<div>
					<p>我是段落1</p>
				</div>
			</div>
		</div>
	</body>
</html>

对以上代码进行操作:

python 复制代码
from bs4 import BeautifulSoup
# bs4 用法
# 1.准备需要解析的数据
html = open('for_bs4.html',encoding='utf-8').read()

# 2.生成基于网页源代码的bs4对象
soup = BeautifulSoup(html,'lxml')

# 3.获取标签
# soup.select()   在整个网页中获取css选择器选中的所以标签
#soup.select_one() 在整个网页中获取css选择器中的第一个标签

result = soup.select('#box1 p')
print(result)
result1 = soup.select_one('#box1 p')
print(result1)

'''
总结:标签对象.select(css选择器)     获取css选择器所有标签,返回一个列表,列表中元素是标签对象
     标签对象.select_one(css选择器)  获取第一个标签,结果是标签对象
'''

result3 =soup.select('p')
#print(result3)

result4 = soup.select('#box2')
#print(result4)

#4. 获取标签内容和标签属性
p = soup.select_one('p')
img = soup.select_one('img')

# a.获取标签内容  标签对象.text
print(p.text)  #肖申克的救赎
# b. 获取标签的属性值
print(img.attrs['src'])
# https://b0.bdstatic.com/ugc/mFgjRS-3T9fHnYC3CAxHHwba8a3cbd3af3e42ddda89fa78b831a5f.jpg@h_1280

二. 爬取豆瓣电影的信息

python 复制代码
from bs4 import BeautifulSoup
import requests
import csv


# 1.获取网页数据
def get_net_data(url: str):
    # headers进行伪装成正常的浏览器访问
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
    }
    # 获取网页代码信息
    response = requests.get(url=url, headers=headers)
    # 返回解析后的代码信息
    return response.text


# 2.解析网页数据
# ol class='grid_view' ->li ->div .item
#这里的html 就是第一步中解析网页代码后的信息
def analyse_data(html: str):
    # 生成基于网页源代码的bs4对象
    soup = BeautifulSoup(html, 'lxml')
    # 将所需要的电影信息代码块都获取下来
    all_films_div = soup.select('.grid_view>li>.item')

    all_data = []
  # 遍历每一个代码块,一个代码块都是一部电影的具体信息
    for div in all_films_div:
        name = div.select_one('.title').text
        info = div.select_one('.bd>p').text.strip().split('\n')[-1].strip()
        time, country, category = info.split('/')
        score = div.select_one('.rating_num').text
        comment_count = div.select('.star>span')[-1].text[:-3]
        intro = div.select_one('.inq').text

        all_data.append([name, score, time.strip(), country.strip(), category.strip(), comment_count, intro])

    f = open('../files/第一页电影数据.csv','w',encoding='utf-8',newline='')
    #创建一个 CSV 文件写入器,并将其关联到一个已经打开的文件对象 f 上,就是在创建的第一页数据电影文件中准备录入信息
    writer = csv.writer(f)
    # 写的是表头 writerow 只写一行
    writer.writerow(['电影名字','评分','上映时间','发行国家地区','类型','评论人数','简介'])
    # csv文件中写入内容
    writer.writerows(all_data)

if __name__ == '__main__':
    # for q in range(0, 251, 25):
    #     url1 = f'https://movie.douban.com/top250?start={q}&filter='

    result = get_net_data(url='https://movie.douban.com/top250') #返回的是 response.text
    analyse_data(result)

三. 爬取250部电影(二只爬取了第一页内容,网站有很多页)

python 复制代码
from bs4 import BeautifulSoup
import requests
import csv


# 1.获取网页数据
def get_net_data(url: str):
    # headers进行伪装成正常的浏览器访问
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
    }
    # 获取网页代码信息
    response = requests.get(url=url, headers=headers)
    # 返回解析后的代码信息
    return response.text


# 2.解析网页数据
# ol class='grid_view' ->li ->div .item
#这里的html 就是第一步中解析网页代码后的信息
def analyse_data(html: str):
    # 生成基于网页源代码的bs4对象
    soup = BeautifulSoup(html, 'lxml')
    # 将所需要的电影信息代码块都获取下来
    all_films_div = soup.select('.grid_view>li>.item')

    all_data = []
  # 遍历每一个代码块,一个代码块都是一部电影的具体信息
    for div in all_films_div:
        name = div.select_one('.title').text
        info = div.select_one('.bd>p').text.strip().split('\n')[-1].strip()
        time, country, category = info.split('/')
        score = div.select_one('.rating_num').text
        comment_count = div.select('.star>span')[-1].text[:-3]
        intro = div.select_one('.inq').text

        all_data.append([name, score, time.strip(), country.strip(), category.strip(), comment_count, intro])

    f = open('../files/250部电影数据.csv','w',encoding='utf-8',newline='')
    #创建一个 CSV 文件写入器,并将其关联到一个已经打开的文件对象 f 上,就是在创建的第一页数据电影文件中准备录入信息
    writer = csv.writer(f)
    # 写的是表头 writerow 只写一行
    writer.writerow(['电影名字','评分','上映时间','发行国家地区','类型','评论人数','简介'])
    # csv文件中写入内容
    writer.writerows(all_data)

'''
在这里有所改变,看下面代码,上面都一样
'''
if __name__ == '__main__':
    for page in range(0, 250, 25):
        url = f'https://movie.douban.com/top250?start={page}&filter='
        result = get_net_data(url=url) #返回的是 response.text
        analyse_data(result)

四. os模块(看创建的文件是否存在,不存在进行创建,这是避免使用open的时候出现文件不存在的报错)

python 复制代码
import os
if not os.path.exists('../files/abc'):
    os.mkdir('../files/abc')

五. 爬取英雄联盟的英雄名字(json)方法

json在netwok 中的 fetch/xhr 中找

python 复制代码
import requests
response = requests.get('https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js')
result = response.json()

for x in result['hero']:
    print(x['name'],x['alias'])
    
    
  • 找到network(网络),然后点击Fetch/XHR

  • 一一找到名称列表的文件,通过preview(预览)查看是否我们需要的数据

  • 查看json数据结构,并获取数据

六.下载安妮的皮肤

python 复制代码
import requests


# 1.定义一个函数
#img:是图片链接
def download(img: str, name: str):
    res = requests.get(img)

    with open(f'../skin/{name}.jpg', 'wb') as f:
     # 因为是图片所有用content
        f.write(res.content)


# 2.主程序入口下载图片
#用的还是json 还是network 下 fetch/xhr找
if __name__ == '__main__':
    response = requests.get('https://game.gtimg.cn/images/lol/act/img/js/hero/1.js')
    result = response.json()

    for x in result['skins']:
        name = x['name']
        img_url = x['mainImg']

        if not img_url:
            img_url = x['chromaImg']

        download(img_url,name)
相关推荐
小爬虫程序猿15 小时前
利用爬虫精准获取淘宝商品描述:实战案例指南
爬虫
奔跑吧邓邓子19 小时前
【Python爬虫(14)】解锁Selenium:Python爬虫的得力助手
开发语言·爬虫·python·selenium
郝开21 小时前
Python 爬虫框架对比与推荐
爬虫·python·网络爬虫
计算机徐师兄2 天前
Python基于Flask的豆瓣电影数据分析可视化系统(附源码,文档说明)
爬虫·python·flask·豆瓣电影·豆瓣电影数据分析可视化系统·豆瓣电影数据分析·python豆瓣电影数据分析
大数据学习爱好者2 天前
基于flask+vue的租房信息可视化系统
大数据·开发语言·爬虫·python·信息可视化
数据小爬虫@2 天前
利用Python爬虫按图搜索1688商品(拍立淘):实战案例指南
爬虫·python·图搜索算法
奔跑吧邓邓子2 天前
【Python爬虫(3)】解锁Python爬虫技能树:深入理解模块与包
开发语言·爬虫·python·模块·
m0_748251722 天前
【论文投稿】Python 网络爬虫:探秘网页数据抓取的奇妙世界
爬虫·python·microsoft
大懒猫软件3 天前
使用 Python 爬虫和 FFmpeg 爬取 B 站高清视频
爬虫·python·ffmpeg
大数据学习爱好者3 天前
python旅游推荐系统+爬虫+可视化(协同过滤算法)
大数据·爬虫·python·深度学习·信息可视化