如何从多个页面抓取数据

How to Data Scrape from multiple pages

import os
from webdriver_manager.chrome import ChromeDriverManager
import time

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--start-maximized')
options.page_load_strategy = 'eager'

driver = webdriver.Chrome(options=options)
url = "https://www.moneycontrol.com/financials/marutisuzukiindia/ratiosVI/MS24#MS24"
driver.get(url)
wait = WebDriverWait(driver, 20)

我想查找现金 EPS 的值(独立的和合并的),但主要问题是页面上只有 5 个值,其他值使用箭头按钮检索直到结束。

如何一次检索这些值?

基于在浏览此景象时查看 URL

https://www.moneycontrol.com/financials/marutisuzukiindia/ratiosVI/MS24/1#MS24

似乎箭头导航到一个新的 URL,在 # 符号前面的 URL 中递增一个数字。

因此,浏览页面如下所示:

Page1: https://www.moneycontrol.com/financials/marutisuzukiindia/ratiosVI/MS24/1#MS24
Page2: https://www.moneycontrol.com/financials/marutisuzukiindia/ratiosVI/MS24/2#MS24
Page3: https://www.moneycontrol.com/financials/marutisuzukiindia/ratiosVI/MS24/3#MS24
etc...

这些单独的 URL 可用于浏览此特定网站。可能这会起作用

def get_pg_url(pgnum):
    return 'https://www.moneycontrol.com/financials/marutisuzukiindia/ratiosVI/MS24/{}#MS24'.format(pgnum)

网络抓取需要调整以适应目标视线。我输入 pgnum=10000,结果显示文本 Data Not Available for Key Financial Ratios。当没有剩余页数时,您可能可以使用此文本来告诉您。

将我的评论进一步添加到代码中。 评论: 这是一个分页元素,它的 href 为“javascript:void();”单击一次超过分页计数。如果数据仍然存在,则它有一个寻呼号码(在这种情况下为 4)。金钱控制。com/financials/marutisuzukiindia/ratiosVI/MS24/…。所以任何一个条件都可以用于退出!

代码中的注释参考建议。

df_list=pd.read_html(driver.page_source) # read the table through pandas
result=df_list[0] #load the result, which will be eventually appended for next pages.

current_page=driver.find_element_by_class_name('nextpaging') # find elment of span 
while True:
    current_page.click()
    time.sleep(20) # sleep for 20 
    current_page=driver.find_element_by_class_name('nextpaging')
    paging_link = current_page.find_element_by_xpath('..') # get the parent of this span which has the href
    print(f"Currentl url : { driver.current_url } Next paging link : { paging_link.get_attribute('href')} ")
    if "void" in paging_link.get_attribute('href'):
        print(f"Time to exit {paging_link.get_attribute('href')}")
        break # exit rule 

    df_list=pd.read_html(driver.page_source)
    result=result.append(df_list[0]) # append the result