首页 > 解决方案 > 使用 R/Python 从 Web 下载数据的非硒方式

问题描述

我正在寻找一些非 Selenium 方法来使用R(最好)或Python.

在 RI 中使用下面的代码来做同样的事情 -

library(rvest)
library(XML)
Link = 'https://www.bseindia.com/stock-share-price/itc-ltd/itc/500875/'
read_html(Link) %>% html_nodes(".textvalue .ng-binding") %>% html_text()
## character(0)

理想情况下,我应该能够获得大部分数值。但正如您所见,它无法下载任何内容。任何指向正确方法的指针都将非常有益。

我也尝试过BeautifulSoup module如下Python没有任何成功-

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
uClient = uReq("https://www.bseindia.com/stock-share-price/itc-ltd/itc/500875/")
page_html = uClient.read()
page_soup = soup(page_html, 'html.parser')
page_soup.findAll("div", {"class":"textvalue.ng-binding"})

谢谢,

标签: pythonrweb-scrapingbeautifulsouprvest

解决方案


这很容易,因为您可以使用页面使用的 API。返回 json 包含所有值,但我只打印一个。

Python:

import requests

r = requests.get('https://api.bseindia.com/BseIndiaAPI/api/StockTrading/w?flag=&quotetype=EQ&scripcode=500875').json()
print(r['MktCapFF'])

回复:

library(rvest)
library(jsonlite)

r <- read_html('https://api.bseindia.com/BseIndiaAPI/api/StockTrading/w?flag=&quotetype=EQ&scripcode=500875') %>%html_text() %>%jsonlite::fromJSON(.)
print(r$MktCapFull)

推荐阅读