且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Scrapy 如何检查给定元素中是否存在某个类

更新时间:2023-11-26 09:01:46

您可以在 XPath 中检查只有一个类的元素:

You could check for an element with only one class like this in XPath:

//li[@class='a']

但这仅查找完全匹配.所以你可以试试:

But that looks for exact matches only. So you could try:

//li[contains(@class, 'a')]

虽然这也将匹配noa"或abig".所以你的最终答案可能是:

Though this will also match "noa" or "abig". So your final answer will probably be:

//li[contains(concat(' ', @class, ' '), ' a ')]

在 Scrapy 中,如果一个 Selector 匹配一些非零内容,它就会评估为真.所以你应该能够写出类似的东西:

In Scrapy, a Selector will evaluate as true if it matches some nonzero content. So you should be able to write something like:

li_tag = response.xpath("//li[contains(concat(' ', @class, ' '), ' a ')]")
if li_tag: 
    print "Yes, I found an 'a' li tag on the page."

主要答案:这里