Python:Selenium chromedriver不适用于按钮单击

时间:2018-09-23 13:05:24

标签: python selenium selenium-webdriver

我希望使用Selenium python单击该按钮,但是出错,以下是我单击该按钮的python代码:

        FileOutputStream out = new FileOutputStream(new File(SRC1));
        InputStream doc = new FileInputStream(new File(SRC));

        XWPFDocument document = new XWPFDocument(doc );
        CTSectPr addNewSectPr = document.getDocument().getBody().addNewSectPr();
        CTPageMar addNewPgMar = addNewSectPr.addNewPgMar();
        addNewPgMar.setLeft(BigInteger.valueOf(720L));
        addNewPgMar.setTop(BigInteger.valueOf(720L));
        addNewPgMar.setRight(BigInteger.valueOf(720L));
        addNewPgMar.setBottom(BigInteger.valueOf(720L));
        document.write(out);
        out.close();

OR

br.find_element_by_css_selector("span[id^='rallybutton-1121-btnIconEl']").click()

OR

br.find_element_by_xpath('//*[@id="rallybutton-1121-btnIconEI"]').click()

AND等也不可行

下面是我的检查元素:

br.find_element_by_xpath('//*[@id="rallybutton-1121"]').click()

enter image description here

我的按钮如下所示:

enter image description here

我希望单击“导出为CSV ...”

enter image description here

错误:

<a class="x4-btn secondary rly-small x4-unselectable x4-btn-default-small x4-icon x4-btn-icon x4-btn-default-small-icon" style="float:right;border-width:0;" hidefocus="on" unselectable="on" tabindex="0" id="rallybutton-1121" role="button">
   <span id="rallybutton-1121-btnWrap" role="presentation" class="x4-btn-wrap" unselectable="on"><span id="rallybutton-1121-btnEl" class="x4-btn-button" role="presentation">

     <span id="rallybutton-1121-btnInnerEl" class="x4-btn-inner x4-btn-inner-center" unselectable="on">&nbsp;</span>

        <span role="presentation" id="rallybutton-1121-btnIconEl" class="x4-btn-icon-el icon-export " unselectable="on" style="">&nbsp;</span>
     </span>
   </span>
</a>

1 个答案:

答案 0 :(得分:2)

您在代码中使用的 ID rallybutton-1121看起来很动态。

您可以使用以下CSS选择器从ID中提取 rallybutton

a[id^='rallybutton']  

代码为:

br.find_element_by_css_selector("a[id^='rallybutton']").click()  

建议:在开发工具中选中a[id^='rallybutton'],只是要确保只有一个条目。

请考虑在代码中添加 WebDriverWait ,以提高稳定性。

希望这会有所帮助。