如果我想爬取商品图片,应该怎么修改代码?

要爬取商品图片,你需要从 HTML 中提取图片的 URL,然后下载图片。以下是修改后的代码示例,展示如何爬取商品图片并保存到本地。

修改后的代码示例

(一)解析 HTML 内容并提取图片 URL

parse_product_details 函数中,添加代码来提取商品图片的 URL。

Python

from bs4 import BeautifulSoup
import requests
import os

def parse_product_details(html):
    soup = BeautifulSoup(html, 'html.parser')
    products = soup.select(".m-itemlist .items .item")
    for product in products:
        title = product.select_one(".title").get_text(strip=True)
        price = product.select_one(".price").get_text(strip=True)
        shop = product.select_one(".shop").get_text(strip=True)
        img_url = product.select_one(".pic .img")['data-src']  # 提取图片 URL
        print(f"商品名称: {title}")
        print(f"商品价格: {price}")
        print(f"店铺名称: {shop}")
        print(f"商品图片: {img_url}")
        print("------------------------")
        download_image(img_url, title)  # 下载图片
(二)下载图片

添加一个函数 download_image,用于下载图片并保存到本地。

Python

def download_image(url, title):
    if not os.path.exists('images'):
        os.makedirs('images')  # 创建保存图片的目录
    try:
        response = requests.get(url)
        if response.status_code == 200:
            # 使用商品标题作为图片文件名,替换非法字符
            filename = ''.join([c for c in title if c.isalnum() or c in (' ', '.')]).rstrip()
            with open(f'images/{filename}.jpg', 'wb') as f:
                f.write(response.content)
            print(f"图片已保存: {filename}.jpg")
    except Exception as e:
        print(f"下载图片时出错: {e}")
(三)整合代码

将上述功能整合到主程序中,实现完整的爬虫程序。

Python

import requests
from bs4 import BeautifulSoup
import os

def get_page(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }
    response = requests.get(url, headers=headers)
    return response.text

def parse_product_details(html):
    soup = BeautifulSoup(html, 'html.parser')
    products = soup.select(".m-itemlist .items .item")
    for product in products:
        title = product.select_one(".title").get_text(strip=True)
        price = product.select_one(".price").get_text(strip=True)
        shop = product.select_one(".shop").get_text(strip=True)
        img_url = product.select_one(".pic .img")['data-src']  # 提取图片 URL
        print(f"商品名称: {title}")
        print(f"商品价格: {price}")
        print(f"店铺名称: {shop}")
        print(f"商品图片: {img_url}")
        print("------------------------")
        download_image(img_url, title)  # 下载图片

def download_image(url, title):
    if not os.path.exists('images'):
        os.makedirs('images')  # 创建保存图片的目录
    try:
        response = requests.get(url)
        if response.status_code == 200:
            # 使用商品标题作为图片文件名,替换非法字符
            filename = ''.join([c for c in title if c.isalnum() or c in (' ', '.')]).rstrip()
            with open(f'images/{filename}.jpg', 'wb') as f:
                f.write(response.content)
            print(f"图片已保存: {filename}.jpg")
    except Exception as e:
        print(f"下载图片时出错: {e}")

def search_products(keyword):
    url = f"https://s.taobao.com/search?q={keyword}"
    html = get_page(url)
    parse_product_details(html)

if __name__ == "__main__":
    keyword = "iPhone 13"
    search_products(keyword)

注意事项和建议

(一)图片 URL 的提取
  • 淘宝商品图片的 URL 可能包含 data-src 属性,这是懒加载的图片地址。确保提取正确的属性值。

  • 如果图片 URL 是相对路径,需要将其转换为绝对路径。

(二)图片下载
  • 使用 requests.get 方法下载图片,并将内容写入文件。

  • 确保文件名合法,避免包含非法字符。

(三)异常处理
  • 在下载图片时,可能会遇到网络请求失败或图片不存在的情况。通过捕获异常来处理这些问题。

(四)遵守网站规则
  • 在爬取数据时,务必遵守淘宝的 robots.txt 文件规定和使用条款,不要频繁发送请求,以免对网站造成负担或被封禁。

通过上述步骤和示例代码,你可以轻松地使用 Python 爬虫获取淘宝商品的详细信息,并下载商品图片。希望这个教程对你有所帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值