使用Python与BeautifulSoup爬取图片URL遇阻,寻求技术帮助
问题分析与解决方法
核心问题
你当前代码在详情页仅获取了图片所在的div容器,没有提取其中img标签的src属性;另外你提供的目标HTML片段是列表页的产品卡片结构,如果想直接在列表页爬图片可以更高效,下面分两种情况给出解决方案:
方案1:修正详情页的图片爬取逻辑
在详情页中,product-main__image-container是图片容器,里面的img标签才存储图片URL,修改代码中提取imgurl的部分:
import requests import pandas as pd import urllib.parse from bs4 import BeautifulSoup import csv baseurl = 'https://www.thewhiskyexchange.com/' productlinks = [] for x in range(1,4): r = requests.get(f'https://www.thewhiskyexchange.com/c/316/campbeltown-single-malt-scotch-whisky?pg={x}') soup = BeautifulSoup(r.content, 'html.parser') tag = soup.find_all('ul',{'class':'product-grid__list'}) for items in tag: for link in items.find_all('a', href=True): productlinks.append(baseurl + link['href']) for items in productlinks: r = requests.get(items) soup = BeautifulSoup(r.content, 'html.parser') name = soup.find('h1', class_='product-main__name').text.strip() price = soup.find('p', class_='product-action__price').text.strip() # 修正:找到容器内的img标签,提取src属性 img_container = soup.find('div', class_='product-main__image-container') if img_container: imgurl = img_container.find('img')['src'] print(f"名称: {name}, 价格: {price}, 图片URL: {imgurl}") else: print(f"产品 {name} 未找到图片")
方案2:直接在列表页爬取图片(更高效)
如果你想爬取的是列表页产品卡片里的图片(即你提供的目标HTML片段),无需进入详情页,直接在列表页解析即可:
import requests from bs4 import BeautifulSoup baseurl = 'https://www.thewhiskyexchange.com/' for x in range(1,4): r = requests.get(f'https://www.thewhiskyexchange.com/c/316/campbeltown-single-malt-scotch-whisky?pg={x}') soup = BeautifulSoup(r.content, 'html.parser') # 找到所有产品卡片的图片容器 img_containers = soup.find_all('div', class_='product-card__image-container') for container in img_containers: img_tag = container.find('img') if img_tag: img_url = img_tag['src'] product_name = img_tag['alt'] print(f"产品名称: {product_name}, 图片URL: {img_url}")
额外提示
- 爬取网站时建议添加请求头(比如
User-Agent),避免被网站限制:headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' } # 请求时传入headers r = requests.get(url, headers=headers) - 注意网站的
robots.txt规则,确保爬取行为合规。
内容的提问来源于stack exchange,提问作者sammyb62
相关产品推荐
相关产品推荐

