Parse pages from html code href in Python

Viewed 24

I have an html, which contains the below code:

<a href="?page=5" title="Go to last page">
            <span class="visually-hidden">Last page</span>
            <span aria-hidden="true">Last »</span>
          </a>

could someone please help me in getting the last page number (5 in this case) using Beautiful Soup? Thanks

1 Answers

You can use str.split on href= property:

last_page = soup.find('a')['href'].split('=')[-1]
print(last_page)

Prints:

5

Or (to select <a> tag with title="Go to last page":

last_page = soup.find('a', title='Go to last page')['href'].split('=')[-1]
print(last_page)
Related