如何将值从给定的URL导入python?

时间:2019-06-11 15:18:19

标签: python json beautifulsoup

2 个答案:

答案 0 :(得分:1)

对于bs4 4.7.1,请使用:has:contains。将:containstd:nth-of-type一起使用以搜索右边的列,然后使用:has检索父行,并再次使用descendant combinatortd:nth-of-type来获取ltp列的值该行。

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=-10006&symbol=NIFTY&symbol=NIFTY&instrument=-&date=-&segmentLink=17&symbolCount=2&segmentLink=17')
soup = bs(r.content, 'lxml')
ltp = soup.select_one('#octable tr:has(td:nth-of-type(12):contains("12000.00")) td:nth-of-type(6)').text.strip()

答案 1 :(得分:0)

import requests
from bs4 import BeautifulSoup

page = requests.get('https://nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=-10006&symbol=NIFTY&symbol=NIFTY&instrument=-&date=-&segmentLink=17&symbolCount=2&segmentLink=17')

soup = BeautifulSoup(page.content,"lxml")

data = []
for tr in soup.select('table#octable tr')[2:-1]:
    data.append([td.text.strip() for td in tr.select('td')])

def get_ltp(data, strike_price):
    for d in data:
        if strike_price == d[11]:
            return d[5]

print(get_ltp(data, '12000.00'))

打印:

25.35