Python Forum
BeautifulSoup4, How to get an HTML tag with specific class.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
BeautifulSoup4, How to get an HTML tag with specific class.
#7
Edit this is merge of Threads,so my answer is same as @stranac.
-----
Can use CSS selectors to match the exact class name.
from bs4 import BeautifulSoup

html = '''\
<img class="this" alt="this" src="this_source1.gif">
<img class="this" alt="this" src="this_source2.gif">
<img class="this" alt="this" src="this_source3.gif">
<img class="this and that" alt="not this" src="this__and_that_source1.gif">
<img class="this and that" alt="not this" src="this__and_that_source2.gif">
<img class="this and that" alt="not this" src="this__and_that_source3.gif">'''

soup = BeautifulSoup(html, 'lxml')
only_this = soup.select('img[class="this"]')
Test:
>>> only_this
[<img alt="this" class="this" src="this_source1.gif"/>,
 <img alt="this" class="this" src="this_source2.gif"/>,
 <img alt="this" class="this" src="this_source3.gif"/>]

>>> [i.get('src') for i in only_this]
['this_source1.gif', 'this_source2.gif', 'this_source3.gif']
Reply


Messages In This Thread
RE: BeautifulSoup4, How to get an HTML tag with specific class. - by snippsat - Nov-22-2018, 05:25 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Div Class HTML selector in Python Artur 1 618 Mar-28-2024, 09:46 AM
Last Post: StevenSnyder
  Beautifulsoup4 help samuelbachorik 1 1,361 Feb-05-2022, 10:44 PM
Last Post: snippsat
  Python Obstacles | Karate | HTML/Scrape Specific Tag and Store it in MariaDB BrandonKastning 8 3,171 Nov-22-2021, 01:38 AM
Last Post: BrandonKastning
  HTML multi select HTML listbox with Flask/Python rfeyer 0 4,652 Mar-14-2021, 12:23 PM
Last Post: rfeyer
  Python3 + BeautifulSoup4 + lxml (HTML -> CSV) - How to write 3 Columns to MariaDB? BrandonKastning 21 6,998 Mar-23-2020, 05:51 PM
Last Post: ndc85430
  Python3 + BeautifulSoup4 + lxml (HTML -> CSV) - How to loop to next HTML/new CSV Row BrandonKastning 0 2,374 Mar-22-2020, 06:10 AM
Last Post: BrandonKastning
  How to get the href value of a specific word in the html code julio2000 2 3,218 Mar-05-2020, 07:50 PM
Last Post: julio2000
  BeautifulSoup4 plugin help Lathem01 2 2,036 Feb-16-2020, 11:56 AM
Last Post: snippsat
  Web crawler extracting specific text from HTML lewdow 1 3,410 Jan-03-2020, 11:21 PM
Last Post: snippsat
  How do I extract specific lines from HTML files before and after a word? glittergirl 1 5,115 Aug-06-2019, 07:23 AM
Last Post: fishhook

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020