【问题标题】:Scrapy: Selector returns full element with .get (but assigns data correctly)Scrapy:选择器返回带有 .get 的完整元素(但正确分配数据)
【发布时间】:2021-03-05 11:46:21
【问题描述】:

我有一些问题需要解决。我尝试用 SO 中发布的类似问题来解决,但它对我不起作用,所以我决定向社区提问。

我意识到我的代码可以正常工作,获取我要求的数据,但是打印给了我整个元素,而不仅仅是我想要的 css 类。

这是我的代码

def parse_links(self, response):

        content = ''

        with open('characters.html', 'r', encoding='utf-8') as f:
            for line in f.read():
                content += line
                
        response = Selector(text=content)
        
        # loop over characters
        for character in response.css('article[class="item item_contains_branding item-multimedia-container"]'):
            print(characters.css('a[class="item-link"]::attr(href)').get)

如您所见,我从网站 .html 创建了一个文件,我想从 css 中获取类项。

当我打印结果时,结果如下:

<bound method SelectorList.get of [<Selector xpath="descendant-or-self::a[@class = 'item-link']/@href" data='/caracteristica/904/?xtmc=1_1_3000&xtcr=0'>]>
<bound method SelectorList.get of [<Selector xpath="descendant-or-self::a[@class = 'item-link']/@href" data='/caracteristica/383/?xtmc=1_1_3000&xtcr=0'>]>
<bound method SelectorList.get of [<Selector xpath="descendant-or-self::a[@class = 'item-link']/@href" data='/caracteristica/916/?xtmc=1_1_3000&xtcr=0'>]>
<bound method SelectorList.get of [<Selector xpath="descendant-or-self::a[@class = 'item-link']/@href" data='/caracteristica/903/?xtmc=1_1_3000&xtcr=0'>]>

如您所见,我获取了例如最后一个'/caracteristica/903/?xtmc=1_1_3000&amp;xtcr=0' 的数据,但我不需要整个句子,只需要获取数据。

希望你能帮助我。

提前致谢。

【问题讨论】:

    标签: python get scrapy css-selectors


    【解决方案1】:

    您正在打印实际 .get 方法的表示,而不是调用它的结果。

    简单来说,您缺少括号:

    print(characters.css('a[class="item-link"]::attr(href)').get())
    

    【讨论】:

    • 这个好像之前肯定已经回答过了,但是我什么都找不到……
    • 哦......我不知道我怎么可能通过那个细节......它工作正常......非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    相关资源
    最近更新 更多