1

I have a issue with looping it is a simple code that should return 7 answers, however it just returns 1 answer (also this answer varies between the 7 options)

Can you see any direct flaws?

Thanks for the help.


import requests
import bs4

my_url = 'http://www.promittere.se/'

res = requests.get(my_url)    

#html parsing
page_soup = bs4.BeautifulSoup(res.text, 'html.parser')

#Container
containers = page_soup.findAll("li")

for container in containers:
    title = container.a.text

print("title: " + title)
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
roa
  • 21
  • 1

2 Answers2

0

Your identation is off.

I would encurage you to read and follow: How to debug small programs (#2) and familiarize yourself with a debugger - they are great tools to fix your errors yourself.


Python uses indented block to group things together - mostly for loops / conditions / try catch / file operations:

  • for in in range(10):
  • if 1==2:
  • try: ... except:
  • with open(...) as f:

or f.e for function/classes/etc.

Your print() command is outside your loop so it will only ever print the last title that was captured in the for loop above it.

Fix it like this:

for container in containers:
    title = container.a.text

    print("title: " + title)  # this needs to be indented to belong _into_ the loop

Be aware that container might not contain anything (on other pages) and that the li-elements also might not contain a "a href" inside (on other pages) - directly accessing container.a.text might give you an error if container does not contain any a - tag.

Use error handling: ask-forgiveness-not-permission-explain to catch errors when they occure to make your code more robust.

See https://docs.python.org/3.6/tutorial/errors.html

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Hi and thank you Patrick. Could you please show me what you mean with My script above? Not shure I understand. This is more or less my first try at scripting. – roa Mar 25 '18 at 18:23
  • @roa - See my answer: **Fix it like this** - I indented the printing so now it belongs to the "body" of the `for`-loop – Patrick Artner Mar 25 '18 at 18:28
0

thank you so much for your help. It was the indentation fails, its corrected and now it works. BR R

roa
  • 21
  • 1