【问题标题】:Creating a css selector to locate multiple ids in a single-shot创建一个 css 选择器以单次定位多个 id
【发布时间】:2019-05-21 22:24:09
【问题描述】:

我在脚本中定义了 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)

【问题讨论】:

    标签: python python-3.x web-scraping css-selectors lxml


    【解决方案1】:

    你可以这样做:

    .rest-list-information div span
    

    但我认为考虑逗号混乱是个坏主意。您不会找到很多没有逗号的样式表。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2012-10-07
        • 1970-01-01
        • 2015-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-04
        • 1970-01-01
        • 2013-07-19
        相关资源
        最近更新 更多