【问题标题】:Get last page number from html using python使用python从html获取最后一页码
【发布时间】:2021-07-07 16:24:29
【问题描述】:

我正在尝试从 html 代码中获取最后一个页码:

<a aria-label="Page 47" class="pg _act">47</a>

url = "https://www.jumia.com.ng/womens-dresses/"

def getLastPageNumber(soup):
  number = []
  for item in soup.find_all("a", class_="pg _act"):
    x = item.text
    number.append(x)
  return max(number)

getLastPageNumber(soup)

每当我运行此代码时,它只返回“1”,如果我将 url 更改为 url = "https://www.jumia.com.ng/womens-dresses/?page=48" ,它会输出 48 . 我想要的是它附加页码并返回最大值。

【问题讨论】:

  • 是否只想获取本页的最后页码?
  • 是的,我想知道它有多少页,因为我想抓取 3000 个数据点。我知道该网站每页的最大标签页数是 48 个。

标签: python html web-scraping beautifulsoup


【解决方案1】:

您可以通过aria-label="Last Page" 获取该元素,并通过正则表达式获取最后一页的编号,代码在这里:

from bs4 import BeautifulSoup
import requests, re

url = "https://www.jumia.com.ng/womens-dresses/"
regex = r"page=(.*)#"
resp = requests.get(url)
soup = BeautifulSoup(resp.text)
target_tag = soup.find("a", {"aria-label": "Last Page"})
print(re.search(regex, target_tag.get("href")).group(1))

这给了我:

50

和页面一样:

【讨论】:

  • 完美。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 2022-11-19
  • 2016-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多