[英]Trying to click all HTML elements in a web page
I am using Selenium and Beautiful Soup to click, and expand, all toggle elements in a single web page. 我正在使用Selenium和Beautiful Soup来单击和扩展单个网页中的所有切换元素。 My code looks like this.
我的代码如下所示。
from selenium import webdriver
import os
chromedriver = "C:\Users\rs\Downloads\chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
url='http://www.coprporate-site.com'
driver.get(url)
driver.find_element_by_class_name('next').click()
I'm guessing it should be something like that. 我猜应该是那样的。 By default, items appear like this:
默认情况下,项目显示如下:
<pan-icon class="a6z-dynamic-tree-node-toggle a6z-dynamic-tree-node-toggle-collapsed" size="treeCtrl.nodeArrowIconSize" icon="sort-descending" role="button"> </pan-icon>
Each object has a small triangle next to it. 每个对象旁边都有一个小三角形。 I'm trying to loop through all items that are in the 'toggle-collapsed' state and change each to 'toggle'.
我试图遍历所有处于“折叠”状态的项目,并将每个项目更改为“折叠”。 I think the code should look like this, below.
我认为代码如下所示。
<pan-icon class="a6z-dynamic-tree-node-toggle" size="treeCtrl.nodeArrowIconSize" icon="sort-descending" role="button"> </pan-icon>
How can I loop through all these specific HTML elements, as described above, and change each one from 'toggle-collapsed' to 'toggle'? 我如何如上所述遍历所有这些特定的HTML元素,并将每个元素从“切换折叠”更改为“切换”? TIA.
TIA。
Selenium's WebDriver package has several methods which allow you to fetch all elements in DOM. Selenium的WebDriver包有几种方法 ,可让您获取DOM中的所有元素。 One of such methods is
find_elements_by_class_name
. 这种方法之一是
find_elements_by_class_name
。 Loop through each element and expand it, ideally the way the human user would - through clicking. 遍历每个元素并将其展开,这是人类用户最好的方式-单击。 Thus, your code could look something like this:
因此,您的代码可能如下所示:
from selenium import webdriver
import os
chromedriver = "C:\Users\rs\Downloads\chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
url='http://www.coprporate-site.com'
driver.get(url)
for element in driver.find_elements_by_class_name('a6z-dynamic-tree-node-toggle-collapsed'):
element.click()
If you need to check whether the class name itself contains 'toggle-collapsed' substring, you could use find_elements_by_xpath
with contains
attribute in the XPath, eg 如果需要检查类名本身是否包含“ toggle-collapsed”子字符串,则可以在XPath中使用带有
contains
属性的find_elements_by_xpath
,例如
for element in driver.find_elements_by_xpath(r"\\*[contains(@class, 'toggle-collapsed')]"):
element.click()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.