【问题标题】:Extracting p tags from a div - Scrapy从 div 中提取 p 标签 - Scrapy
【发布时间】:2021-10-10 04:54:39
【问题描述】:

我希望使用 Scrapy 从以下 HTML 代码中提取类别和标题:

<div class="box-text box-text-products">
  <div class="title-wrapper">       
     <p class="category uppercase is-smaller no-text-overflow product-cat op-7">Supplements     </p>
     <p class="name product-title"><a href="https://martslu.com/product/explosive-energy-pre-workout-cherry-punch-300g/">Explosive Energy Pre Workout Cherry Punch – 300g</a></p></div><div class="price-wrapper">
</div>      
</div>

以下是我写的代码

    def parse(self,response):
        for product in response.css('div.box-text.box-text-products::text'):
            yield{
                'category': product.css('div.title-wrapper.p::text').get(),
                'title': product.css('div.title-wrapper>p.name product-title::text').get()}

我仍然不清楚如何在 p 标签中指出特定的类名。任何帮助表示赞赏。

【问题讨论】:

  • 提供的信息不足,div.box-text 在您提供的 html 中不存在。
  • 已更新,请查收。

标签: python scrapy css-selectors


【解决方案1】:
def parse(self,response):
    for product in response.css('div.box-text.box-text-products'):
        yield {
            'category': product.css('div.title-wrapper > p.category::text').get(),
            'title': product.css('div.title-wrapper > p.product-title > a::text').get()
        }

您不熟悉 CSS 选择器。谷歌一些材料并学习语法。

scrapy 中的解析依赖于 parsel,它引入了 2 个额外的自定义非标准伪元素

  • ::text
  • ::attr(name)

除了这 2 个自定义伪元素之外,还支持大多数 css 选择器语法。

【讨论】:

  • 非常感谢,我意识到我在 response.css() 的 css 选择器中犯的愚蠢错误
猜你喜欢
  • 2015-12-26
  • 2021-06-23
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多