2

Is it possible to do something like this in python:

I have a single 'span' that I want to scrape.

I just want to simplify how I get the data, I will get an error if I convert the bs4 instance to text if it is None. and in general it would be nice if python had some kind of functionality like this. :-)

note = x.text for event.find('span', {'class': 'header-3'}) as x if not None else ''

Thank you in advance!

Edit:

So far i solved my issue with bs4 by making a function that i can apply on all my bs4 instances:

get_text = lambda x: x.text.strip() if x is not None else ''
note = get_text(event.find('span', {'class': 'header-3'}))

But it would still be nice to know if there was a nice way like the one in my first codeblock.

mama
  • 735
  • 3
  • 13
  • You need a list comprehension. Possible dupe: https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it – Austin Sep 12 '20 at 12:55
  • Sorry I think I wasnt clear in my question. I am not working with a list. This is a single entity – mama Sep 12 '20 at 13:15

1 Answers1

1

Is this what you are looking for?

event = BeautifulSoup(response.text, 'html.parser')
note = event.findAll('span', {'class': 'header-3'})
B. Bogart
  • 770
  • 5
  • 11
  • Sorry I think I wasnt clear in my question. I am not working with a list. This is a single entity – mama Sep 12 '20 at 13:15
  • Are you asking how to get the one and only span with class: header-3 as text if it exists? Some example data and the expected results would help figure out what you need. – B. Bogart Sep 13 '20 at 11:55
  • So here is an example just to show a working example, but what I really wanted to ask is if there is a way to do what I did without the lambda function. Some kind of fancy python feature or different thinking that lets me write one line less :-) https://codeshare.io/5O1k3x – mama Sep 13 '20 at 19:44
  • I see. I think the lambda is the most elegant and readable way. I can think of several other possibilities, but none result in one less line of code :) – B. Bogart Sep 15 '20 at 11:48