使用BeautifulSoup4爬取丝芙兰阿联酋站数据报错求助
问题排查与修复
核心错误原因
- 本地运行的
TypeError是因为误用了find_all方法:find_all会返回所有匹配元素组成的列表,不能直接用["content"]这种字符串下标取属性,取单个匹配元素应该用find方法。 - repl.it平台无有效数据是因为使用的Chrome 44版本User-Agent太旧,被目标站反爬策略拦截,返回的页面没有有效商品数据;另外从url.txt读取的链接末尾默认带换行符,未清理就发起请求也会导致请求异常。
- 额外问题:meta标签的
content是属性值,不需要调用.text获取;部分元素的选择器和Sephora阿联酋站的实际页面结构不匹配。
修复后完整代码
import requests from bs4 import BeautifulSoup import json import time def sephora(url): # 清理链接末尾的换行符和空白 url = url.strip() HEADERS = ({ # 替换为较新的UA,避免被反爬拦截 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5' }) try: # 增加超时设置,避免请求卡住 webpage = requests.get(url, headers=HEADERS, timeout=10) webpage.raise_for_status() # 主动抛出请求异常 except Exception as e: print(f"请求失败: {url}, 错误信息: {str(e)}") return soup = BeautifulSoup(webpage.content, 'html.parser') # 品牌名 try: brand = soup.find('span', {"class": "brand-name"}).get_text(strip=True) except AttributeError: brand = 'NA' # 商品名 try: prname = soup.find('meta', {"itemprop": "name"})["content"] except (AttributeError, KeyError): prname = 'NA' # 价格 try: price = soup.find('meta', {"itemprop": "price"})["content"] except (AttributeError, KeyError): price = 'NA' # 货币 try: price_cur = soup.find('meta', {"itemprop": "priceCurrency"})["content"] except (AttributeError, KeyError): price_cur = 'NA' # SKU try: item_code = soup.find('meta', {"itemprop": "sku"})["content"] except (AttributeError, KeyError): item_code = 'NA' # 商品链接 try: urll = soup.find('meta', {"itemprop": "url"})["content"] except (AttributeError, KeyError): urll = 'NA' # 分类 try: category = soup.find('span', {"class": "product-name"}).get_text(strip=True) except AttributeError: category = 'NA' # 规格 try: size = soup.find('img', {"class": "variation-image"})["alt"] except (AttributeError, KeyError): size = 'NA' # 图片信息 img_src = img_title = img_alt = 'NA' try: image_tag = soup.find("a", {"class": "variation-display-name", "rel": "nofollow"}) imagess = image_tag["data-lgimg"] res = json.loads(imagess) img_src = res.get('url', 'NA') img_title = res.get('title', 'NA') img_alt = res.get('alt', 'NA') except Exception: pass # 描述 try: desc_div = soup.find('div', {"class": "product-description-box"}).get_text(strip=True) except AttributeError: desc_div = 'NA' # 写入文件,用with自动管理文件句柄 with open("out.csv", "a", encoding="utf-8-sig") as f: row = f"{url};{brand};{prname};{category};{urll};{desc_div};{price};{price_cur};{img_src};{img_title};{item_code};{size}\n" f.write(row) print(f"写入完成: {prname}") # 增加请求间隔,避免触发反爬 time.sleep(2) if __name__ == '__main__': # 先写表头 header = "URL;BRAND;NAME;CATEGORY;VARIANT LINK;DESCRIPTION;PRICE;PRICE CUR;IMG;TITLE;ITEMCODE;SIZE\n" with open("out.csv", "w", encoding="utf-8-sig") as f: f.write(header) # 读取链接列表 with open("url.txt", "r", encoding="utf-8") as f: urls = f.readlines() for link in urls: sephora(link)
额外注意事项
- 确保
url.txt里每行放一个商品链接,不要有多余空行 - 使用utf-8-sig编码写入是为了避免用Excel打开csv时出现乱码问题
内容的提问来源于stack exchange,提问作者Mohd Salman
相关产品推荐
相关产品推荐

