Reputation: 998
I have the following HTML
<!DOCTYPE html>
<html>
<body>
<div class="w-30-ns W-100 pp">
<h1>My First Heading</h1>
</div>
<div class="w-30-ns W-100 pp">
<h1>My Second Heading</h1>
</div>
<div class="w-30-ns W-100 pp">
<h1>My Third Heading</h1>
</div>
</body>
</html>
I would like to iterate thru all "class pp" webelements and find "h1" classes. This is of course a simplified version of what I am trying to do. The pp classes have MANY more children elements that I need to find and look at. Creating a list up-front of all the "pp" web-elements would be great.
The code I have been trying is:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
url2 = 'C:\\Users\\ed821\\Downloads\\TEST2.html'
driver = webdriver.Chrome()
driver.get(url2)
titles = driver.find_elements_by_class_name("pp")
for title in titles:
heading = title.find_element_by_class_name("h1") # << NoSuchElementException
print("Title is:" + heading.text)
When I get to the "heading =" line, there is "NoSuchElementException".
Running in VSCode on Windows 10.
Upvotes: 0
Views: 134
Reputation: 3987
You can try this :
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
url2 = 'C:\\Users\\ed821\\Downloads\\TEST2.html'
driver = webdriver.Chrome()
driver.get(url2)
titles = driver.find_elements_by_class_name("pp")
for title in titles:
heading = title.find_element_by_tag_name("h1")
print("Title is:" + heading.text)
You are trying to search h1
by class name but h1
is tag name!
You can learn more about find_element_by_tag_name
from here
And you can learn more about other find_element_by_<>
functions from official documentation.
Upvotes: 1