【问题标题】:Incorporating pagination scraping into my script将分页抓取合并到我的脚本中
【发布时间】:2022-11-11 01:18:17
【问题描述】:
url = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1313&_nkw=electronics"

response = requests.get(url)

soup = BeautifulSoup(response.text, "html.parser")

names = soup.find_all("div", class_="s-item__title")

prices = soup.find_all("span", class_="s-item__price")

shippings = soup.find_all("span", class_="s-item__shipping s-item__logisticsCost"


for name,price,shipping in zip(names,prices,shippings):
    print(name.text, price.text, shipping.text)

现在,这个脚本完美运行。它打印需要打印的所有内容。 但是...我希望能够转到下一页并将那里的所有内容也刮掉。 下一页的类是“pagination__next icon-link” 我不确定我会怎么做。

【问题讨论】:

    标签: python web-scraping beautifulsoup pagination


    【解决方案1】:

    只需通过分页 url 查询值迭代链接

    base_url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=electronics&_pgn='
    for i in range(pages_count):
        base_url+f'{i}'
    
        # your code...
        response = requests.get(url)
    
    

    为了按类别正确解析,由于站点显示页面的具体情况,我建议您参考每个请求的分页对象,查看最后一个页码并在请求中替换它

    获取当前页面上的最后一个可用页面数:

    ol = soup.find("ol", class_="pagination__items")
    lis = ol.find_all("li")
    
    print(f"Last available number of post on current page {lis[-1].text}")
    

    【讨论】:

    • 是的,但是使用soup.select_one 来点击“下一页”图标呢?
    • 为了什么?您还需要解析给定 url 的所有页面。使用计数器和布尔状态创建一个 while 循环。如果连续 2 页的最后一页相同,则将状态更改为 false 并完成剩余的页面。
    • bs4 不是 selenium,bs4 是一个刮板,它不能发出点击(不像 selenium)。所以需要通过url遍历所有页面,每次更新最后一页,检查是否是最后一页(这个是专门针对ebay的,分页不给最后页码)
    • 我不能提供反馈,但当我可以的时候,我一定会的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多