首页 > 解决方案 > 从 Python 中的 html 代码 href 解析页面

问题描述

我有一个 html,其中包含以下代码:

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

5有人可以帮助我使用 Beautiful Soup获取最后一个页码(在这种情况下)吗?谢谢

标签: pythonbeautifulsoup

解决方案


您可以str.splithref=财产上使用:

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

印刷:

5

或者(用 选择<a>标签title="Go to last page"

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

推荐阅读