Python爬虫---使用BeautifulSoup下载麦当劳点餐图片

步骤:

  1. 导入需要使用的包

  2. 定位正确的url地址

  3. 发请求

  4. 获取响应

  5. 解析响应的内容

  6. 将获取的xpath语法转换成bs4语法

7.下载图片

python 复制代码
import urllib.request
from bs4 import BeautifulSoup

# url
url = "https://www.mcdonalds.com.cn/index/Food/menu/burger"

# 请求
response = urllib.request.urlopen(url=url)

# 响应
content = response.read().decode("utf-8")
# print(content)

# 解析
soup = BeautifulSoup(content, "lxml")

# img_list = "//div[@class="pic"]/img/@src"    # xpath语法
# name_list = "//div[@class="col-md-3 col-sm-4 col-xs-6"]//span/text()"   # xpath语法

name_list = soup.select("div[class='col-md-3 col-sm-4 col-xs-6'] span")  # BeautifulSoup语法
img_list = soup.select(".pic>img")
# print(type(name_list))
# print(name_list, len(name_list))
# print(img_list)

# for name in name_list:
#     print(name.get_text())  # 每个名字
#     print(name.string)  # 每个名字
#     print(name_list.index(name))  # 每个名字的索引

for img in img_list:
    # print(img["src"])  # 每张图片的地址
    img_src = img["src"]
    # print(img_list.index(img))   # 每个图片的索引
    # name = img_src.split("/")[-1]  # 图片命名
    name = name_list[img_list.index(img)].get_text()  # 图片命名
    urllib.request.urlretrieve(url=img_src, filename="./image/1/" + name + ".jpg")  # 下载图片
    print(f"图片{name}下载了")
相关推荐
biter down24 分钟前
9:JSONSchema
python
日晨难再35 分钟前
C语言&Python&Bash&Tcl:全局变量和局部变量
c语言·python·bash·tcl
麻雀飞吧38 分钟前
期货量化主连和具体合约怎么切:天勤 KQ.m 与 KQ.i 用法
python·区块链
先吃饱再说41 分钟前
Python List 切片与 LLM Prompt 设计:从数据结构到接口调用
python
一只专注api接口开发的技术猿1 小时前
OpenClaw 对接淘宝商品 API,低成本实现全天候选品监控|附可运行 Python 实操代码
大数据·开发语言·数据库·python
xingpanvip1 小时前
星盘接口开发文档:马盘次限盘接口指南
android·开发语言·python·php·lua
FBI HackerHarry浩1 小时前
第二阶段Day07【Python生成器、yield关键字、property、正则表达式】
开发语言·python·正则表达式
梦想不只是梦与想1 小时前
Python 中的 4 种作用域
python·作用域
coderwei1232 小时前
从OpenAI到Strip:用六大支柱读懂Harness Engineering的生产实践
python·ai·ai编程
海鸥-w2 小时前
Python(FastAPI)中ORM框架Sqlalchemy的安装及建表
python