Python Iterator Reference + lxml

I have this script -

import lxml
from lxml.cssselect import CSSSelector
from lxml.etree import fromstring
from lxml.html import parse



website = parse('http://example.com').getroot()


selector = website.cssselect('.name')


for i in range(0,18): 
    print selector[i].text_content() 

      

As you can see, the for loop stops after a few times, which I asked beforehand. I want the for loop to stop only after it has printed everything.

+1


a source to share


3 answers


The CSSSelector.cssselect () method returns an iterable, so you can simply do:



for element in selector:
    print element.text_content()

      

+5


a source


What about

for e in selector:
    print e.text_content()

      



?

+2


a source


I would expect that you need a for loop like:

selectors = website.cssselect('.name , .name, .desc')

for selector in selectors: 
    print selector.text_content()

      

+2


a source







All Articles