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)
相关推荐
IT毕设实战小研15 小时前
基于大数据的WTA职业网球赛事演变与竞技格局数据可视化分析
大数据·后端·爬虫·python·信息可视化·课程设计
2601_9623824315 小时前
用“爬虫”抓取小红书内容侵权吗 福建法院判明边界
爬虫·数字经济·知识产权·不正当竞争·福建法院
Mycdn_WD15 小时前
从 AI 爬虫变多了到 AI 抓取开始分流,CDN 行业进入下一阶段
人工智能·爬虫·cdn·pcdn·城域网·pcdn资源招募
该逃避避1 天前
爬虫代理配置指南:从0搭建Crawl4AI网页爬虫教程
爬虫
TechWayfarer1 天前
Cloudflare 9·15新政倒计时:用IP风险画像识别AI爬虫,防止误伤Googlebot
网络·人工智能·爬虫·python·tcp/ip·网络安全
susplus2 天前
【HTTP协议】HTTP介绍及基础【C语言爬虫实现】
c语言·爬虫·http·万维网
绘梨衣5472 天前
AI技术栈全景指南_Prompt_RAG_爬虫_MCP
人工智能·爬虫·prompt
stolentime3 天前
OpenClaw 2.0 新手快速上手与实战指南
爬虫·python·ai·网络爬虫
玫瑰互动GEO3 天前
工程视角看GEO优化与SEO优化:爬虫排序 vs 大模型引用
人工智能·爬虫·搜索引擎
for_ever_love__3 天前
python爬虫: 数据解析
开发语言·爬虫·python·xpath