【问题标题】:How to know the last page number website in web scrape in beautifulsoup?如何知道beautifulsoup中网页抓取的最后一个页码网站?
【发布时间】:2020-03-04 17:56:23
【问题描述】:

我正在从 Flipkart 抓取数据,我想在其中抓取所有产品的名称、价格和评级。所以我想从所有页面中抓取所有必需的信息。 此链接共有 11 页: https://www.flipkart.com/mobiles/mi~brand/pr?sid=tyy%2C4io&otracker=nmenu_sub_Electronics_0_Mi 那么我怎样才能循环直到我到达页面的末尾,即直到第 11 页码。

【问题讨论】:

  • 欢迎来到 StackOverflow,请编辑问题以包含您尝试过的内容以及遇到的具体问题。

标签: python web beautifulsoup scrape


【解决方案1】:
from bs4 import BeautifulSoup
import requests
from itertools import zip_longest


def mxnum():
    r = requests.get(
        "https://www.flipkart.com/mobiles/mi~brand/pr?sid=tyy%2C4io&otracker=nmenu_sub_Electronics_0_Mi")
    soup = BeautifulSoup(r.text, 'html.parser')
    for item in soup.findAll("div", {'class': '_2zg3yZ'}):
        mxnum = list(item.strings)[0].split(" ")[-1]
    return int(mxnum) + 1


mxnum = mxnum()


def Parse():
    with requests.Session() as req:
        names = []
        prices = []
        rating = []
        for num in range(1, mxnum):
            print(f"Extracting Page# {num}")
            r = req.get(
                f"https://www.flipkart.com/mobiles/mi~brand/pr?sid=tyy%2C4io&otracker=nmenu_sub_Electronics_0_Mi&page={num}")
            soup = BeautifulSoup(r.text, 'html.parser')
            for name in soup.find_all("div", {'class': '_3wU53n'}):
                names.append(name.text)
            for price in soup.find_all("div", {'class': '_1vC4OE _2rQ-NK'}):
                prices.append(price.text[1:])
            for rate in soup.find_all("div", {'class': 'hGSR34'}):
                rating.append(rate.text)
    for a, b, c in zip_longest(names, prices, rating):
        print("Name: {}, Price: {}, Rate: {}".format(a, b, c))


Parse()

【讨论】:

  • 是的,我通过使用从 1 到 11 的 for 循环使这成为可能,但在这里我必须从网站手动知道最后一个页码。我想让它动态识别最后一个页码。
  • 非常感谢先生的努力!
  • @SunilThakur 很高兴为您提供帮助。如果它满足您的需求,请随时通过勾选答案旁边的耐克标记来接受我的回答。
【解决方案2】:

第 1 页到第 11 页的 url 定义为:

https://www.flipkart.com/mobiles/mi~brand/pr?sid=tyy%2C4io&otracker=nmenu_sub_Electronics_0_Mi&page={n}

    where n is from 1 to 11

因此,您可以创建一个循环,其中 n=1 到 11,并将 n 替换为循环中的当前值。

【讨论】:

  • 是的,我通过使用从 1 到 11 的 for 循环使这成为可能,但在这里我必须从网站手动知道最后一个页码。我想让它动态识别最后一个页码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-25
相关资源
最近更新 更多