Scrapy 如何检查给定元素中是否存在某个类 [英] Scrapy How to check if certain class exists in a given element

查看:37
本文介绍了Scrapy 如何检查给定元素中是否存在某个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<li class="a">category1</li>
<li>subcatergory1</li>
<li>subcatergory2</li>
<li class="a">category2</li>
<li>subcatergory1</li>
<li>subcatergory2</li>

我正在遍历一个 ul,它包含两种 li,一种有 a 类,另一种没有.我想知道是否有一种现有的方法来检查给定 li 中是否存在 a 类,而不是提取类值并手动进行比较.

I'm looping through an ul which contains 2 kinds of li, one has a class and one doesn't. I'm wondering is there an existing method to check if the a class exists in a given li, rather than extracting class value and compare it manually.

for li in ul
    if (li has class:a)
        ....

如有任何想法,我们将不胜感激.

Any thoughts would be appreciated.

推荐答案

您可以在 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."

主要答案:这里

这篇关于Scrapy 如何检查给定元素中是否存在某个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆