【问题标题】:How can I scrape table and find out corresponding entry for maximum number in particular column?如何抓取表格并找出特定列中最大数量的相应条目?
【发布时间】:2018-06-13 12:37:58
【问题描述】:

如何从“https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=-9999&symbol=BANKNIFTY&symbol=BANKNIFTY&instrument=OPTIDX&date=-&segmentLink=17&segmentLink=17”中抓取表格

然后找出“PUTS”下的最大“OI”,最后在该行中找到该特定最大OI的相应条目

直到打印行:

import urllib2
from urllib2 import urlopen
import bs4 as bs

url = 'https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=-9999&symbol=BANKNIFTY&symbol=BANKNIFTY&instrument=OPTIDX&date=-&segmentLink=17&segmentLink=17'

html = urllib2.urlopen(url).read()
soup = bs.BeautifulSoup(html,'lxml')
table = soup.find('div',id='octable')
rows = table.find_all('tr')
for row in rows:
print row.text

【问题讨论】:

  • 如果您要将其标记为 python 问题,是否要添加 python 代码?
  • 如果你愿意,那就去做吧 :) 这里是如何提问:stackoverflow.com/help/how-to-ask
  • @Drako 感谢您的链接,下次会记住并编辑问题。
  • @cricket_007add the code..can't move forward with find maximum and below

标签: python web-scraping


【解决方案1】:

您必须在<tr> 中迭代所有<td>。你可以用一堆 for 循环来做到这一点,但使用 list comprehension 更简单。只使用这个:

oi_column = [
    float(t[21].text.strip().replace('-','0').replace(',',''))
    for t in (t.find_all('td') for t in tables.find_all('tr'))
    if len(t) > 20
]

在表的所有<tr> 中迭代所有<td>,只选择那些超过20 个项目的行(排除最后一行)并执行文本替换或任何您想要满足您的要求的内容,在这里转换文字浮动

整个代码是:

from bs4 import BeautifulSoup
import requests

url = 'https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=-9999&symbol=BANKNIFTY&symbol=BANKNIFTY&instrument=OPTIDX&date=-&segmentLink=17&segmentLink=17'

response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")

tables = soup.find("table", {"id":"octable"})

oi_column = [
    float(t[21].text.strip().replace('-','0').replace(',',''))
    for t in (t.find_all('td') for t in tables.find_all('tr'))
    if len(t) > 20
]
#column to check
print(oi_column)

print("max value : {}".format(max(oi_column)))
print("index of max value : {}".format(oi_column.index(max(oi_column)))) 

#the row at index
root = tables.find_all('tr')[2 + oi_column.index(max(oi_column))].find_all('td')
row_items = [
    (
        root[1].text.strip(),
        root[2].text.strip()
        #etc... select index you want to extract in the corresponding rows
    )
]
print(row_items)

你可以找到一个额外的例子来废弃这样的表格here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多