【问题标题】:Is there a way to get all tags that have a class attribute in python using scrapy?有没有办法使用scrapy在python中获取所有具有类属性的标签?
【发布时间】:2021-05-17 03:46:43
【问题描述】:

假设我有一个 html 页面,它有许多不同的属性,它们都具有相同的类:

<a href = "www.example1.com" class = "example-class" Example Text 1 />
<a href = "www.example2.com" class = "example-class" Example Text 2 />
<a href = "www.example3.com" class = "example-class" Example Text 3 />

是否可以获取所有具有“example-class”类的文本的所有文本?所以在这种情况下,示例文本 1、示例文本 2 和示例文本 3。

谢谢

【问题讨论】:

    标签: python html scrapy


    【解决方案1】:

    是的,您可以这样做:

    def parse(self, response):
        texts = response.css('a.example-class::text').getall()
        for text in texts:
            print(text)
    

    scrapy 中的 CSS 选择器

    a.example-class::text 将定位具有 example-class 类的 &lt;a&gt; 元素,::text 是 scrapy 中的一个特殊选择器,它将提取这些选择器的文本内容。

    但是,您写道您的元素看起来像:

    <a href = "www.example1.com" class = "example-class" Example Text 1 />
    

    看起来有点奇怪,通常链接应该是这样的:

    <a href = "www.example1.com" class = "example-class">Example Text 1</a>
    

    如果你写错了上面的scrapy代码应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 2012-01-31
      • 2017-10-12
      • 2013-09-04
      • 1970-01-01
      • 2017-06-15
      • 1970-01-01
      相关资源
      最近更新 更多