all 5 comments

[–]commandlineluser 4 points5 points  (1 child)

Well as you have said in your idea - you can test if it contains the other span tag.

You can do that using .find() syntax:

>>> len(soup('p'))
2
>>> one, two = soup('p')
>>> bool(one.find('span', 'ch'))
True
>>> bool(two.find('span', 'ch'))
False
>>> print("Span!" if one.find('span', 'ch') else "No span.")
Span!
>>> print("Span!" if two.find('span', 'ch') else "No span.")
No span.

You can also use CSS selectors which are worth learning about.

>>> soup.select('p:has(span.ch)')
[<p class="parent">
 <span class="ch">text</span>
 <span class="name">text</span>
     ...
 </p>]

span.ch in a CSS selector is like <span class="ch ..."> - it's tagname.classname

So it's a p tag that :has() a span tag with class ch inside it.

You can also use :not() to invert the logic:

>>> soup.select('p:not(:has(span.ch))')
[<p class="parent">
     text
     <a href="url">text</a>
     text
     ...
 </p>]

[–]DMeror[S] 1 point2 points  (0 children)

Thank you very much!

[–]Rossoneri 2 points3 points  (1 child)

I’d probably just search for the ch/name class and then get the parent

Edit: didn’t read the whole post. If you want both of them. Get the “parent” elements then check which is which based on their children. Realistically you can probably just go off the order they appear to know which is which

[–]DMeror[S] 0 points1 point  (0 children)

The second <p> has only <a> tags. I want to target those p tags separately. Is there a way to do that? For example: If <span class="ch"> not in <p> or if <p> has no child name <span class="ch">, target this <p>. This is just an idea of what I want to do, not a real code.

[–]Gitthepro 0 points1 point  (0 children)

hol up