How to select a few tags with attributes (BeautifulSoup, python)

Viewed 28

I need to get inner text from p tags, inner text from h2 tags and inner html from img tags. Only this tags.

I tried such code:

tags = section.find_all(['p', 'img', 'h2' ])

but, first: i need not all "source" tags, only with special attributes second: i can`t use tag.text, because i need to get another attr from img

I can`t process tags separately too , because i need keep order.

How can i get:

First string
Second string
<img src="xxx.jpg">
Third string

from

<p>First string</p>
<p>Second string</p>
<img type="one" src="xxx.jpg">
<img type="two" src="yyy.jpg">
<p>Third string</p>
1 Answers

Simply, filter them out.

For example,

from bs4 import BeautifulSoup

sample = """<p>First string</p>
<p>Second string</p>
<img type="one" src="xxx.jpg">
<img type="two" src="yyy.jpg">
<p>Third string</p>"""

for item in BeautifulSoup(sample, "html.parser").find_all(["p", "img"]):
    if item.name == "p":
        print(item.getText(strip=True))
    if item.name == "img" and item["type"] == "one":
        print(item)

Output:

First string
Second string
<img src="xxx.jpg" type="one"/>
Third string
Related