【问题标题】:python specify css selectorpython指定css选择器
【发布时间】:2016-03-29 21:46:59
【问题描述】:

网页有代码:

<table>
  <tbody>
   <tr>
    <td>
     <time data-timestamp="1458895194718" title="2016-03-25 11:39:54<small    class="milliseconds">.718</small>">11:39</time>
    </td>
    <td>
     <span class="invisep"><</span>
     <mark class="nickname" style="cursor:pointer;  color:#03DC03">usernickname</mark>
     <span class="invisep">></span>
    </td>

我需要获得 style= 并且我收到了使用建议:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.webdriver import FirefoxProfile


    colorelement = driver.find_element_by_css_selector('mark.nickname')
    color = colorelement.get_attribute('style')

它可以工作,但我的代码只返回找到的第一个值。网页有很多块,每个人都有块 代码find_elements_by_css_selector 返回“AttributeError: 'list' object has no attribute 'get_attribute'” 你能帮我吗,我怎样才能得到第二个(第三个等)值,或者它可以一次找到所有值

【问题讨论】:

  • 您拥有的代码使用find_element_*,即使有多个匹配项,它也只返回第一个匹配项。听起来您想要find_element**s**_*,它将返回所有匹配的元素。请参阅下面 Florent B. 的回答。

标签: python-3.x selenium css-selectors webdriver


【解决方案1】:

您需要为每个元素调用 get_attribute:

elements = driver.find_elements_by_css_selector('mark.nickname')
for element in elements:
  print element.get_attribute('style')
  print color

或者使用列表理解:

elements = driver.find_elements_by_css_selector('mark.nickname')
colors = [element.get_attribute('style') for element in elements]
for color in colors:
  print color

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    相关资源
    最近更新 更多