创建一个css选择器以在一个单独的窗口中定位多个id

2024-05-01 22:07:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我在脚本中定义了css选择器,以获取span元素中的文本,并相应地获取它们。然而,我尝试的方式肯定是混乱的。我只是用逗号分隔了不同的css选择器,让脚本理解我在追求这个或那个。你知道吗

如果我选择xpath,我可以使用'div//span[.="Featured" or .="Sponsored"]',但是在css选择器的情况下,我找不到任何类似的东西来达到相同的目的。我知道用'span:contains("Featured"),span:contains("Sponsored")'我可以得到文本,但像往常一样,中间有逗号。你知道吗

使用css选择器(逗号除外)定位元素(在不同id中)的理想方法是什么?

到目前为止,我的尝试是:

from lxml.html import fromstring

html = """
<div class="rest-list-information">
    <a class="restaurant-header" href="/madison-wi/restaurants/pizza-hut">
        Pizza Hut
    </a>
    <div id="featured other-dynamic-ids">
        <span>Sponsored</span>
    </div>
</div>
<div class="rest-list-information">
    <a class="restaurant-header" href="/madison-wi/restaurants/salads-up">
        Salads UP
    </a>
    <div id="other-dynamic-ids border">
        <span>Featured</span>
    </div>
</div>
"""

root = fromstring(html)
for item in root.cssselect("[id~='featured'] span,[id~='border'] span"):
    print(item.text)

Tags: 文本div脚本id元素html选择器css
2条回答

如果您只是想从HTML中获取所有“span”文本,那么以下内容就足够了:

root_spans = root.xpath('//span')

for i, root_spans in enumerate(root_spans):
    span_text = root_spans.xpath('.//text()')[0]
    print(span_text)

你可以做:

.rest-list-information div span

但我认为把逗号弄乱是个坏主意。你不会找到很多没有逗号的样式表。你知道吗

相关问题 更多 >