Tutorial :Python Iterator Help + lxml



Question:

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 number of times that I set beforehand. I want the for loop to stop only after it has printed everything.


Solution:1

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

for element in selector:      print element.text_content()  


Solution:2

What about

for e in selector:      print e.text_content()  

?


Solution:3

I would expect you want a for loop like:

selectors = website.cssselect('.name , .name, .desc')    for selector in selectors:       print selector.text_content()  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »