title: Checking for attributes in BeautifulSoup?
body: <p>I'm parsing some data from HTML by walking through elements at a certain level using nextSibling, and doing different things depending on the tag name and class of each element encountered. </p>
  
  <p>e.g.,</p>
  
  <pre><code>if n.name == "p" and n.class == "poem": blah()
  </code></pre>
  
  <p>But this raises an error if the element doesn't have a class or if it isn't an instance of Tag and hence has no name.</p>
  
  <p>Testing before accessing like this </p>
  
  <pre><code>if "name" in n:
  </code></pre>
  
  <p>always return false. I could check the type of the object returned by nextSibling to try to weed out NavigableString and Comment, but there's got to be an easier way. </p>
  
  <p>EDIT</p>
  
  <p>Emailed the dev of BeautifulSoup with this question and he recommended testing with </p>
  
  <pre><code>n.get("class")
  </code></pre>
  
  <p>which returns None if "class" is unset, which makes it possible to just do:</p>
  
  <pre><code>if n.get("class") == "poem": blah()
  </code></pre>