[英]How can I select a specific element on a page when there is so many of that element? Selenium webdriver python;
Essentially what I am trying to do is select just the "Reply" box which circled in red, but there are many of these in the page overall.基本上我想做的是 select 只是红色圈出的“回复”框,但整个页面中有很多。 My aim is to be able to select the first "Reply" box on every page.
我的目标是能够 select 每页上的第一个“回复”框。 How can I select just the first reply box for every post (with this link just being an example)?
我怎样才能 select 只是每个帖子的第一个回复框(此链接仅作为示例)?
Currently this doesn't seem to work:目前这似乎不起作用:
reply = driver.find_element_by_xpath("//*[@id='content']/div/div[2]/div/div/div/div[1]/article/div/aside/ul/li[1]/div/div[2]/div/ul/li[7]/button/span/img")
reply.click()
Many thanks.非常感谢。
First way:第一种方式:
The XPath to locate any of that replay buttons is XPath 定位任何重播按钮是
//button[@title="Reply"]
So the XPath to locate the first replay button is所以定位第一个重播按钮的 XPath 是
(//button[@title="Reply"])[1]
So you can simply所以你可以简单地
driver.find_element_by_xpath('(//button[@title="Reply"])[1]').click()
Second way:第二种方式:
With the XPath above you can retrieve a list of all the replay buttons and then get the first element in the list and click on it as following:使用上面的 XPath,您可以检索所有重播按钮的列表,然后获取列表中的第一个元素并单击它,如下所示:
replay_buttons = driver.find_elements_by_xpath('//button[@title="Reply"]')
replay_buttons[0].click()
You can use css_selector instead of XPath here as well:您也可以在这里使用 css_selector 代替 XPath :
replay_buttons = driver.find_elements_by_css_selector('button[title="Reply"]')
replay_buttons[0].click()
Inspecting the page i saw that the class name of this button is: <button class="Button Button--link">
检查页面我看到这个按钮的 class 名称是:
<button class="Button Button--link">
So you can use driver.find_elements_by_class_name('Button Button--link')
, which returns a list of all the buttons.因此,您可以使用
driver.find_elements_by_class_name('Button Button--link')
,它返回所有按钮的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.