通过\u类\u名称查找\u元素\u,当元素明显存在时,返回NoTouchElementException

2024-05-23 14:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Selenium编写一个脚本,该脚本应该定期从Box:https://osu.app.box.com/v/covid-19publicdata下载这个.csv文件,但是我在查找button元素时遇到了问题

按钮的HTML代码如下所示:

<button class="btn tooltip-target tooltip-element-attached-top tooltip-element-attached-center tooltip-target-attached-bottom tooltip-target-attached-center" type="submit" data-resin-item_id="725957383895" data-resin-target="download" tabindex="0"><span class="btn-content"><span>Download</span></span></button>

为了找到按钮并单击它,我编写了以下代码(在导入适当的库后运行):

driver = webdriver.Chrome('C:/Users/calle/chromedriver')
driver.get("https://osu.app.box.com/v/covid-19publicdata")
button = driver.find_element_by_class_name("btn tooltip-target tooltip-element-attached-top tooltip-element-attached-center tooltip-target-attached-bottom tooltip-target-attached-center")
button.click()

然而,尽管我搜索的类名与驱动程序上的类名完全相同,但它在“find element”行上返回NoSuchElementException。我还没有找到任何关于为什么会发生这种情况的信息。我不是一个计算机科学家,所以在这方面的任何帮助都将不胜感激。我也不太喜欢这种特殊的方法,所以如果有更简单的方法,我会洗耳恭听


Tags: https脚本boxapptargetdriverbuttonelement
2条回答

代码的问题是它是一个复合类名,是多个类名。它不适用于类名。有一个更容易使用的选择器

button=driver.find_element_by_css_selector("button[data-resin-target='download']")
button.click()

尝试使用XPATH

webdriver.Chrome('C:/Users/calle/chromedriver')
driver.get("https://osu.app.box.com/v/covid-19publicdata")
button = driver.find_element_by_xpath('//*[@id="app"]/div[5]/span/div/main/div/div/div[1]/header/div/div/button/span/span')
button.click()

相关问题 更多 >