1

I wrote a code to scrape all h4 elements from a homepage.

// Wikipedia is only an example.
browser.get("https://en.wikipedia.org/wiki/Main_Page")
time.sleep(5)
datei = open("bayern.csv", "a")
elems = browser.find_elements_by_css_selector("h4.name")
for elem in elems:
    print(elem)

In my command line I get this output:

<selenium.webdriver.remote.webelement.WebElement (session="f1ef1ee5904aa8b3279e6bf9adb62d34", element="0.09001580038742651-1") >

But I want the content of all h4 elements. Can you tell me why I get this strange output?

2
  • What strange output? Why do you think h4.name would match all h4 elements?
    – jonrsharpe
    Apr 23, 2019 at 20:18
  • Yes i want to get the content of all h4 elements. For Exampel: <h4 class="name">Max Mustermann</h4> I want to get back Max Mustermann
    – Manu
    Apr 23, 2019 at 20:19

2 Answers 2

6

You are trying to print the web element itself, instead of the text it contains.

Try:

elems = browser.find_elements_by_css_selector("h4.name")
for elem in elems:
    print(elem.text)
2
  • I couldn't get users code to actually get any H4 elements, but elms = driver.find_elements_by_xpath('//h2') finds H2 headers, and then your elem.text works as expected. beat me to the answer, :-)
    – Brian W
    Apr 23, 2019 at 20:32
  • @BrianW the URL is just a placeholder I think. :)
    – S Ahmed
    Apr 23, 2019 at 20:51
0

for convenience, webdriver has a find_elements_by_tag_name method:

elems = browser.find_elements_by_tag_name('h4')
for elem in elems:
    print(elem.text)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.