首页 > 解决方案 > 在 Python 中使用 Requests 和 LXML 进行抓取时如何选择“加载更多结果”项

问题描述

我正在抓取网页。该网页由 48 个条目组成。在 48 个条目之后,它会给出一个加载更多结果按钮。我需要从此页面获取所有产品。我该怎么做?对于抓取,我使用 Python、LXML 和请求库。

我会感谢你的帮助。

我的代码:

import requests
from lxml import html
home_page = requests.get('https://www.anntaylor.com/')
website_tree = html.fromstring(home_page.content)
categories = website_tree.xpath('//a[@role="menuitem"]')
def my_function(urls):
    category_page = requests.get(urls)
    category_tree = html.fromstring(category_page.content)
    product_data = category_tree.xpath('//div[@class="product-wrap"]') #//div[@class='product-wrap']
    
    for title in product_data:
        print(title.xpath('.//@href')[0])
        # //link[@rel="next"]
    
    print(len(product_data))
    print(urls)
for i in categories:
    urls = i.xpath('./@href')
    # print(urls[0])
    my_function(urls[0])
print(len(categories))

标签: pythonweb-scrapingpython-requestslxml

解决方案


您使用代码请求的页面没有按钮,但向下滚动时会显示“加载更多”信息栏。我想你想加载页面的全部内容来解析产品的数据。

这篇文章可能会对您有所帮助: Scrape entire scrolling-load page with Python Requests


推荐阅读