问题
I am trying to select an element in selenium using python and need some help with css selector. Here is the HTML code:
<div class="grid x5" id="grid">
<div style="opacity: 1;"><span class="box" style="z-index:92"></span>8</div><div style="opacity: 1;"><span class="box" style="z-index:77"></span>23</div><div style="opacity: 1;"><span class="box" style="z-index:93"></span>7</div><div style="opacity: 1;"><span class="box" style="z-index:99"></span>1</div><div style="opacity: 1;"><span class="box" style="z-index:80"></span>20</div><div style="opacity: 1;"><span class="box" style="z-index:76"></span>24</div><div style="opacity: 1;"><span class="box" style="z-index:83"></span>17</div><div style="opacity: 1;"><span class="box" style="z-index:94"></span>6</div><div style="opacity: 1;"><span class="box" style="z-index:87"></span>13</div><div style="opacity: 1;"><span class="box" style="z-index:95"></span>5</div>
<div style="opacity: 1;"><span class="box" style="z-index:78"></span>22</div><div style="opacity: 1;"><span class="box" style="z-index:98"></span>2</div><div style="opacity: 1;"><span class="box" style="z-index:82"></span>18</div><div style="opacity: 1;"><span class="box" style="z-index:79"></span>21</div><div style="opacity: 1;"><span class="box" style="z-index:89"></span>11</div><div style="opacity: 1;"><span class="box" style="z-index:91"></span>9</div><div style="opacity: 1;"><span class="box" style="z-index:85"></span>15</div><div style="opacity: 1;"><span class="box" style="z-index:90"></span>10</div><div style="opacity: 1;"><span class="box" style="z-index:81"></span>19</div><div style="opacity: 1;"><span class="box" style="z-index:96"></span>4</div>
<div style="opacity: 1;"><span class="box" style="z-index:97"></span>3</div><div style="opacity: 1;"><span class="box" style="z-index:75"></span>25</div><div style="opacity: 1;"><span class="box" style="z-index:88"></span>12</div><div style="opacity: 1;"><span class="box" style="z-index:84"></span>16</div><div style="opacity: 1;"><span class="box" style="z-index:86"></span>14</div>
</div>
One thing I can see is that in style="z-index:92" --> the 100 - z-index is the number being displayed. Not sure how this helps.
if I trying to using selenium and click on the number 1 - 25 using the code above, how would I go about do it with the HTML code presented above?
Added a picture of how it looks
Thanks for you help!
回答1:
text 1-25 is contained in div tag, you can try:
#xpath
element_list = driver.find_elements_by_xpath("//div[contains(@style,'opacity')]")# to find all div elements with style= "opacity: 1;"
#css selector
#element_list = driver.find_elements_by_css_selector("[style^=opacity]") # to match divs containing style attribute starting with opacity
for items in element_list:
print (items.text) #to print out element text
if (items.text) in range(1, 25):
# do your click action here
来源:https://stackoverflow.com/questions/52429771/selecting-an-element-with-css-selector-python