Greediness of execution of applications?

I have something similar using BeautifulSoup:

for line in lines:
    code = l.find('span', {'class':'boldHeader'}).text
    coded = l.find('div', {'class':'Description'}).text
    definition = l.find('ul', {'class':'definitions'}).text
    print code, coded, def

However, not all elements always exist. I can conclude this in an attempt, except that it does not interrupt the execution of the program as follows:

for line in lines:
    try:
      code = l.find('span', {'class':'boldHeader'}).text
      coded = l.find('div', {'class':'Description'}).text
      definition = l.find('ul', {'class':'definitions'}).text
      print code, coded, def
    except:
      pass

But how do I execute statements in a greedy way? For example, if only two elements are available codeand coded, I just want to get them and continue execution. At the moment, even if codethey codedexist, if they defdo not exist, the print command will never be executed.

One way to do this is to put try...exceptfor each statement like this:

for line in lines:
    try:
      code = l.find('span', {'class':'boldHeader'}).text
    except:
      pass
    try:
      coded = l.find('div', {'class':'Description'}).text
    except:
      pass
    try:
      definition = l.find('ul', {'class':'definitions'}).text
    except:
      pass
    print code, coded, def

But this is an ugly approach, and I need something cleaner. Any suggestions?

+3
2

"" :

def get_txt(l,tag,classname):
    try:
        txt=l.find(tag, {'class':classname}).text
    except AttributeError:
        txt=None
    return txt

for line in lines:
    code = get_txt(l,'span','boldHeader')
    coded = get_txt(l,'div','Description')
    defn = get_txt(l,'ul','definitions')
    print code, coded, defn

PS. def defn, def - Python. SyntaxError.

. :

try:
    ....
except:
    ...

, . , :

try:
    ...
except AttributeError as err:
    ...
+3

, "" , . l.find None, . .

, , - HTML-, , . python, , () .

- :

elementsToCheck = [
                  [ 'span', {'class':'boldHeader'} ],
                  [ 'div', {'class':'Description'} ],
                  [ 'ul', {'class':'definitions'} ]]

concatenated = ''
for line in lines:
    for something in elementsToCheck
       element = l.find(something[0], something[1])
       if element is not None
          concatenated += element.text
print concatenated

, , .:)

+3

Source: https://habr.com/ru/post/1773414/


All Articles