【问题标题】:lxml tree.xpath() scraping product description of single product from flipkart results in scraping of all product's descriptionlxml tree.xpath() 从flipkart抓取单个产品的产品描述会导致抓取所有产品的描述
【发布时间】:2021-03-14 05:48:41
【问题描述】:

我尝试在 Flipkart 中使用 lxml 方法 xpath 为每个产品的产品描述创建一个嵌套列表

    product_descriptions = []
    for des in tree.xpath('//ul[@class="_1xgFaf"]'):
      description=[]
      for i in des.xpath('//li[@class="rgWa7D"]/text()'):
        description.append(i)
      product_descriptions.append(description)

    for i in product_descriptions:
      print(i)

但这会导致获取页面中所有的li[@class="rgWa7D"],而不是获取一个

    元素的所有
  • 元素。

【问题讨论】:

  • 仅供参考,“报废”意味着像垃圾一样扔掉东西 - 你想要的术语是 scraping
  • @barny 打错了。无论如何,谢谢你通知我。

标签: python web-scraping xpath lxml


【解决方案1】:

以/ 开始您的XPath 意味着上下文是根文档,这就是为什么您的第二个XPath 在页面中返回所有具有类“rgWa7D”的li 元素。如果您希望上下文是当前的 ul 元素,由变量 des 引用,请将 . 添加到 XPath 的开头:

for i in des.xpath('.//li[@class="rgWa7D"]/text()'):
    description.append(i)

【讨论】:

  • @NikhilVijay 没问题。如果它解决了相关问题,请不要忘记接受答案
猜你喜欢
  • 2019-07-29
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 1970-01-01
  • 2016-10-19
相关资源
最近更新 更多