for loop to iterate over the table rows of track listing in a wikipedia page in python

Here is an example code using BeautifulSoup to extract the track listing table from a Wikipedia page and loop through each row:

main.py
import requests
from bs4 import BeautifulSoup

url = 'https://en.wikipedia.org/wiki/The_Dark_Side_of_the_Moon'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')

table = soup.find_all('table', {'class': 'tracklist'})[0] # Find track listing table
rows = table.find_all('tr') # Get all rows

for row in rows:
    cols = row.find_all('td') # Get columns for each row
    if cols: # Skip header row with no td tags
        track_num = cols[0].get_text().strip()
        track_name = cols[1].get_text().strip()
        track_length = cols[2].get_text().strip()
        print(f'{track_num} - {track_name} ({track_length})')
652 chars
18 lines

This code retrieves the track listing table from a Wikipedia page (in this case, the album "The Dark Side of the Moon"), uses BeautifulSoup to extract all rows, and then loops through each row to extract the track number, name, and length from the corresponding td tags. The if cols: statement skips the header row of the table, which does not contain any td tags. The resulting information is printed for each track using an f-string.

gistlibby LogSnag