如何使用selenium驱动程序

时间:2017-08-31 05:41:34

标签: python selenium

我对selenium python真的很陌生,并坚持一个我无法弄清楚的问题。请有人帮忙。我想要定位此按钮并单击它,但问题是页面上还有其他按钮具有完全相同的类ID等,这两个按钮之间只有1个区别。

aria-label=""

我要点击的aria-label内的文字以

开头
dislike this video

文本是动态的,但起点只是下面描述的数字更改相同。我只想定位此按钮并单击它,因为两个按钮具有完全相同的类,所以我觉得只有这个标记可以被定位和点击。我可以告诉我如何定位起始文本甚至(不喜欢)会起作用。然后单击按钮。下面是按钮代码。

<button is="paper-icon-button-light" id="button" class="style-scope ytd-toggle-button-renderer style-text" aria-label="dislike this video along with 14,279 other people" aria-pressed="false">

我尝试了这段代码,但只有在文字完全匹配时才能正常工作

driver.find_element_by_css_selector('button[aria-label="dislike this video along with 14,279 other people"]').click()

所以上面标签中的数字会发生变化,但它不起作用。

简单来说,有2个按钮具有完全相同的类等,但我想点击第二个按钮。如何用selenium python做到这一点?

按钮1 html代码

<button is="paper-icon-button-light" id="button" class="style-scope ytd-toggle-button-renderer style-text" aria-label="like this video along with 31,427 other people" aria-pressed="false"><yt-icon class="style-scope ytd-toggle-button-renderer"><svg viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" style="pointer-events: none; display: block; width: 100%; height: 100%;" class="style-scope yt-icon"><g class="style-scope yt-icon">
    <path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1.91l-.01-.01L23 10z" class="style-scope yt-icon"></path>
  </g></svg></yt-icon><paper-ripple class="style-scope paper-icon-button-light circle">


<div id="background" class="style-scope paper-ripple" style="opacity: 0;"></div>
<div id="waves" class="style-scope paper-ripple"></div>

按钮2 html代码

<button is="paper-icon-button-light" id="button" class="style-scope ytd-toggle-button-renderer style-text" aria-label="dislike this video along with 14,279 other people" aria-pressed="false"><yt-icon class="style-scope ytd-toggle-button-renderer"><svg viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" style="pointer-events: none; display: block; width: 100%; height: 100%;" class="style-scope yt-icon"><g class="style-scope yt-icon">
    <path d="M15 3H6c-.83 0-1.54.5-1.84 1.22l-3.02 7.05c-.09.23-.14.47-.14.73v1.91l.01.01L1 14c0 1.1.9 2 2 2h6.31l-.95 4.57-.03.32c0 .41.17.79.44 1.06L9.83 23l6.59-6.59c.36-.36.58-.86.58-1.41V5c0-1.1-.9-2-2-2zm4 0v12h4V3h-4z" class="style-scope yt-icon"></path>
  </g></svg></yt-icon><paper-ripple class="style-scope paper-icon-button-light circle">


<div id="background" class="style-scope paper-ripple" style="opacity: 0.00416;"></div>
<div id="waves" class="style-scope paper-ripple"></div>

2 个答案:

答案 0 :(得分:0)

您尝试使用以下css -

driver.find_element_by_css_selector('button[aria-label^="dislike this video"]').click()

或使用xpath -

 driver.find_element_by_xpath('//button[starts-with(@aria-label,"dislike this video")]').click()

答案 1 :(得分:0)

尝试以下xpath -

(//*[@id="button"]/yt-icon)[2]