【爬虫】第三部分 BeautifulSoup

【爬虫】第三部分 BeautifulSoup



3. BeautifulSoup

pip install bs4

pip install lxml

3.1 基础语法

from bs4 import BeautifulSoup

# 通过解析本地文件,讲解基础语法
# 在这里需要注意:默认打开文件的编码格式是gbk,所以需要进行编码
soup = BeautifulSoup(open('test.html',encoding='utf-8'),'lxml')

# find()函数的使用
# 查找a标签 返回的是第一个满足条件的数据
print(soup.find('a')) 

# 查找a标签中对应的属性
print(soup.find('a',title='123'))

# 如果查找的是class属性那么需要加_
print(soup.find('a',class_='456'))

# -------------------------------------------------

# find_all()函数的使用
# 查找所有a标签,返回的是一个列表
print(soup.find_all('a'))

# 查找多个标签,返回的是一个列表
print(soup.find_all(['a','li']))

# 限制查找出数据的条数
print(soup.find_all('li',limit=2))


# --------------------------------------------------

# select()函数 常用
# 查找所有的a标签,返回的是一个列表
print(soup.select('a'))

# 查找类名为123,返回的是一个列表
print(soup.select('.hello123'))

# 查找id为brand
print(soup.select('#brand'))

# 查找title属性
print(soup.select("li[title]"))

# 查找title属性,值为apple
print(soup.select('li[title="apple"]'))

# 查找ul后代的li
print(soup.select('ul li'))

# 查找div子代span
print(soup.select('div > span'))

# 查找div下a和li
print(soup.select('a','li'))

# 获取节点内容
obj = soup.select('a')[0]
print(obj.get_text())

# 获取标签名
obj2 = soup.select('a')[0]
print(obj.name)

# 获取标签上所有的属性,返回的是一个字典
obj3 = soup.select('a')[0]
print(obj.attrs)

3.2 案例 获取产品图片和产品名称

import json
from bs4 import BeautifulSoup
import urllib.request
import os
url = 'https://www.xxx.com.cn/menu'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
    'Referer': 'https://www.xxx.com.cn/stores/?features=&bounds=119.1887%2C26.009707%2C119.411688%2C26.150476',
    'Cookie': 'ZHh6ku4z=A3bqDhOEAQAAP3Owyx6cjm4VElccgubng2EZsDgtJhh_IM8rie-wZ9DXNx_4AdpCW8OucjsbwH8AAEB3AAAAAA|1|1|0d419d3380e67f60a651a064d437c446c5b5fcc2; _ga=GA1.3.1074223427.1666767061; _gid=GA1.3.1116073795.1666767061; _gat_UA-16990907-1=1'
}

# 伪装
request = urllib.request.Request(url=url, headers=headers)

handler = urllib.request.HTTPHandler()
opener = urllib.request.build_opener(handler)
response = opener.open(request).read().decode('utf-8')

# 整理出我们想要的数据
soup = BeautifulSoup(response, 'lxml')
coffee_name = soup.select('ul[class="grid padded-3 product"] strong')
for name in coffee_name:
    with open('data/coffee.txt', 'a+', encoding='utf-8') as fs:
        fs.write(name.get_text()+'\n')


# https://www.starbucks.com.cn
# https://www.starbucks.com.cn/images/products/cold-brew-malt.jpg

# 拿到json数据
imgJson = urllib.request.urlopen('https://www.xxx.com.cn/assets/search/menu-source-zh.json').read().decode('utf-8')

# 遍历拿到我们想要的路径
for item in json.loads(imgJson).values():
    # 拼接图片路径
    imag_url = 'https://www.xxx.com.cn' + item['preview']

    # 获取文件名
    fileName = os.path.split(item["preview"])[1]
    
    # 拼接文件的完整路径
    file_name = f'./data/image/{fileName}'
    urllib.request.urlretrieve(url=imag_url,filename=file_name)


总结

以上就是今天要讲的内容,希望对大家有所帮助!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值