#๐Ÿ”’ accessing field of an object in list comprehension causes AttributeError.

15 messages ยท Page 1 of 1 (latest)

mortal epoch
#

Following snippet

resp.raise_for_status()
soup = BeautifulSoup(resp.text, 'html.parser')
titles = [tr.find("a").text for tr in soup.find(class_="article-table").find_all("tr")[1:]]
``` causes ```
AttributeError                            Traceback (most recent call last)
Cell In[14], line 8
      6 resp.raise_for_status()
      7 soup = BeautifulSoup(resp.text, 'html.parser')
----> 8 titles = [getattr(tr.find("a"), 'text') for tr in soup.find(class_="article-table").find_all("tr")[1:]]
      9 titles

AttributeError: 'NoneType' object has no attribute 'text'
``` I assume that this is because type of tr.find() is not known at the time of evaluation. However, why would python of all language care about it? I mean, it diesnt need to know type to call .find method, and if tr would not have it then it will throw an error. Why is that different?
wheat sparrowBOT
#

@mortal epoch

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

mortal epoch
#

Clarification, the error message is not for the actual snippet. AFter getting the original error I tried using getattr as a proxy thinking that maybe a function call will be allowed

#

same error though

lean thicket
#

it actually does tell you what type it was at evaluation, NoneType, so tr.find("a") must have returned None

mortal epoch
#

But When i print the list it doesnt contain none

#

Oh, nevermind - you are right, somehow there is one None. Dumb me, i put too much trust into consistency of this html

#

?close

lapis houndBOT
#

This is not a Modmail thread.

mortal epoch
#

?resolve

#

wait, how do i kill the thread?

lean thicket
#

o just use ! as the prefix

mortal epoch
#

!close

wheat sparrowBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.