selenium - webcrawler- find_elements_by_css_selector(webelement).text does not work but need an iterator. why?

Viewed 60

as the question suggests why is the below wrong code would not work but the correct code would?

arent they eseentially the same thing? i looked around and saw the post that explained that the python native list works but the selenium created object list in this case will not work

But i did not really understand it in its essence, could anyone please elaborate alittle further in plain english for a novice programmer please

Wrong Code:

mainText = driver.find_elements_by_css_selector(
    'div.post_content.clearfix > p').text
    print(mainContentDetail)

List has no attribute text

Correct code:

mainText = driver.find_elements_by_css_selector(
    'div.post_content.clearfix > p')
for mainContentDetail in mainText:
    print(mainContentDetail.text)
1 Answers

When you use below, you rae trying to list of elements with css selector matching with div.post_content.clearfix > p.

driver.find_elements_by_css_selector(
    'div.post_content.clearfix > p')

And when you write below, you are trying to get the text from multiple elements. But text method works to get the text associated with a single element. As you are trying to get the Text from multiple elements using text method it throws error.

driver.find_elements_by_css_selector(
    'div.post_content.clearfix > p').text

Where as in below code you have list element to a list called mainText and you are iterating through each element in mainText list and and then getting the text from each element using text method. hence it works.

mainText = driver.find_elements_by_css_selector(
    'div.post_content.clearfix > p')
for mainContentDetail in mainText:
    print(mainContentDetail.text)
Related