如何从多个页面抓取数据

时间:2021-04-18 03:14:14

标签: python python-3.x python-2.7 web-scraping selenium-chromedriver

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)

我想找到现金每股收益(独立和合并)的价值,但主要问题是,页面上只有 5 个值,其他值通过箭头按钮检索直到结束。

如何一次性检索这些值?

2 个答案:

答案 0 :(得分:1)

基于在浏览此景点时查看网址

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...

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

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。当没有剩余页面时,您可能可以通过此文本告诉您。

答案 1 :(得分:1)

将我的评论进一步深入到代码中。 评论: 这是一个分页元素,它将 href 获取为“javascript:void();”一旦点击超过分页计数。如果数据仍然存在,则它在那里有一个分页编号(在这种情况下参考 4)。 moneycontrol.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
   

enter image description here