2

In Python, I am using BeautifulSoup to parse text. I want to save a set of 'str' objects into a list. The following code won't run, but the idea should come across:

listings = soup.find_all('h6')
for i in listings:
    projecturls[i] = i.find_all('a', href=True)[0]['href']

So I want to cycle through the elements 'listings' and extract a string. I then want to save this string into projecturls, which I want to be a list. But I get the following error:

NameError: name 'projecturls' is not defined

How do I define this? Or is there a better way to do what I want?

I suppose that dynamically defining N variables would also work, but it is not preferred.

2
  • It looks like 'projecturls' is a dictionary. Add projecturls={} right above that loop to inittialize this loop. Commented May 24, 2014 at 3:13
  • 1
    Did you define projecturls? Commented May 24, 2014 at 3:13

2 Answers 2

2

Define projecturls as a list object, then use list.append method to add an item there:

listings = soup.find_all('h6')
projecturls = [] # <-------------
for i in listings:
    url = i.find_all('a', href=True)[0]['href']
    projecturls.append(url) # <------
Sign up to request clarification or add additional context in comments.

Comments

2

You could also use list comprehension:

listings = soup.find_all('h6')
projecturls = [i.find_all('a', href=True)[0]['href'] for i in listings]

Or map function:

listings = soup.find_all('h6')
projecturls = list(map(lambda i: i.find_all('a', href=True)[0]['href'], listings))

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.