【问题标题】:How to club child elements inside the same div tag together in CSS?如何在 CSS 中将同一 div 标签内的子元素组合在一起?
【发布时间】:2019-12-22 22:20:05
【问题描述】:

我正在尝试使用 Selenium 创建与来自https://www.brainyquote.com/quote_of_the_dayhttps://www.brainyquote.com/quote_of_the_day 的每个引用和作者相关的主题列表。

目前,由于每条引用正好有 4 个主题,所以我可以这样做:

total_topics = [topic.text for topic in driver.find_elements_by_css_selector("""div.col-xs-4.col-md-4 a.qkw-btn.btn.btn-xs.oncl_list_kc""")] 
    grouped_topics = [] 
    for i in range( int(len(total_topics)/4) ):
        grouped_topics.append(total_topics[4*i:4*i+4])

问题在于,可能存在每个引用少于或多于 4 个主题的情况,其中该程序将失败。 网站上主题子部分的 HTML 代码是:

<div class="col-xs-4 col-md-4">
 <div class="qotd-q-cntr">
  <div class="m-brick grid-item boxy bqQt">
   <div class="qll-bg">
    <h2 class="qotd-h2">Quote of the Day</h2>
    <div class="qll-dsk-kw-box">
     <div class="kw-box">
      <a href="/topics/life-quotes" class="qkw-btn btn btn-xs oncl_list_kc" data-idx="0">Life</a>
      <a href="/topics/you-quotes" class="qkw-btn btn btn-xs oncl_list_kc" data-idx="1">You</a>
      <a href="/topics/purpose-quotes" class="qkw-btn btn btn-xs oncl_list_kc" data-idx="2">Purpose</a>
      <a href="/topics/alive-quotes" class="qkw-btn btn btn-xs oncl_list_kc" data-idx="3">Alive</a>

如何在同一个 div 标签中加入所有锚标签文本?希望我能把我的观点带回家。

【问题讨论】:

    标签: python html selenium css-selectors


    【解决方案1】:

    将搜索一分为二,找到主题的容器和主题

    grouped_topics = []
    quotes = driver.find_elements_by_css_selector('div.col-xs-4.col-md-4 div.qll-dsk-kw-box')
    for quote in quotes:
        topics = quote.find_elements_by_css_selector('a.qkw-btn.btn.btn-xs.oncl_list_kc')
        grouped_topics.append([topic.text for topic in topics])
    

    【讨论】:

    • 我不知道我们可以对这样的元素进行嵌套搜索!一直认为只有driver 可以用来访问元素。
    • @ChaoSAdm webelement 也有 find_element_by_* 方法。在 Java 中,您会看到它实现了 SearchContext,它提供了搜索功能。
    猜你喜欢
    • 1970-01-01
    • 2016-11-01
    • 2021-03-15
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2018-12-10
    • 1970-01-01
    相关资源
    最近更新 更多