pythonweb-scrapingbeautifulsoup

How to set filter in the bs4 soup on the basis of the file extension?


I successfully wrote to get every file detail from a wiki category by beautiful soup4 in python. The category contains .jpg and .pdf file extensions. How can i filter to get details of the pdf-files only?

The code ;-

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup

rUrl  = u'https://commons.wikimedia.org/wiki/Category:பண்டிதர் க. அயோத்திதாசர்'

#getting all the data from above the category url
rData = requests.get(rUrl)
soup = BeautifulSoup(rData.content, 'lxml')

#getting files name only
for item in soup.find_all('div', class_='gallerytext'):
    fileTags = item.a
    print(fileTags.text)
#getting pdfs name only

Its output ;-

Oru paisa tamilan 1.jpg
Oru paisa tamilan 2.jpg
ஒரு பூர்வ பௌத்தனின் சாட்சியம்-அயோத்திதாசரின் சொல்லாடல்.pdf
க. அயோத்திதாஸப் பண்டிதர் சிந்தனைகள்-1.pdf
க. அயோத்திதாஸப் பண்டிதர் சிந்தனைகள்-2.pdf
க. அயோத்திதாஸப் பண்டிதர் சிந்தனைகள்-4.pdf
க. அயோத்திதாஸப் பண்டிதர் சிந்தனைகள்-அரசியல்-சமூகம்.pdf
பண்டிதரின் கொடை-விகிதாச்சார உரிமை எனும் சமூகநீதிக் கொள்கை.pdf

How can filter pdf files only?


Solution

  • Try this to get only the pdf links. I used selector to make the parser focus on those links which have this .pdf in the end.

    import requests
    from bs4 import BeautifulSoup
    
    rUrl  = 'https://commons.wikimedia.org/wiki/Category:பண்டிதர் க. அயோத்திதாசர்'
    
    rData = requests.get(rUrl)
    soup = BeautifulSoup(rData.content, 'lxml')
    
    for item in soup.select(".gallerytext a[href$='.pdf']"):
        print(item['href'])
    

    Or without using selector:

    for item in soup.find_all(class_="galleryfilename"):
        if ".pdf" in item.get('href'):
            print(item['href'])