Scrapy XPath无法获取完整希腊语商品标题问题咨询
问题原因及解决方案
核心问题分析
- 爬取页面错误:你代码中
start_urls指向的是「Herbalife F1 Θρεπτικά Meal Bars σοκολάτα」的商品页,而你要获取的是另一款咖啡拿铁味代餐奶昔的标题,页面不匹配自然得不到目标内容。 - XPath路径写法错误:循环内的XPath用
//开头是从整个HTML文档根节点查找,而非在当前product节点范围内搜索,正确写法应该用.//表示相对当前节点的路径(虽然单商品页面暂时没出问题,但多商品场景会出错)。
修正后的代码
import scrapy class FitcoupleSpider(scrapy.Spider): name = 'fitcouple' allowed_domains = ['fitcouple360.gr'] # 替换为目标商品的正确URL start_urls = ['https://fitcouple360.gr/product/herbalife-formula-1-cafe-latte-550g/'] def parse(self, response): products = response.xpath(".//div[@class='content-page container']/div[contains(@class,'single-product product')]") for product in products: # 使用相对路径获取标题 title = product.xpath(".//div[@class='fixed-content']/h1/text()").get() print(title)
内容的提问来源于stack exchange,提问作者usman Abbasi
相关产品推荐
相关产品推荐

