2020 年 12 月更新:
I have:
- 实现了整个 FnO 宇宙的完全自动化、分钟级数据收集。
- 自动适应不断变化的 FnO 宇宙、退出和新条目。
- 在非市场时间关闭。
- 节假日关闭,包括新宣布的节假日。
- 在年度 Muhurat 交易数据期间自动启动。
我对网络抓取有点陌生,不习惯“tr”和“td”的东西,因此有这个疑问。我试图从这个线程'https://www.quantinsti.com/blog/option-chain-extraction-for-nse-stocks-using-python'在我的Python 3中复制这个Python 2.7代码。
这段旧代码使用 .ix 进行索引,我可以使用 .iloc 轻松更正。但是,行
显示错误“需要类字节对象,而不是 'str'”,即使我在
.
我已经检查过这个其他的link https://stackoverflow.com/questions/33054527/python-3-5-typeerror-a-bytes-like-object-is-required-not-str-when-writing-t来自 stackoverflow 并不能解决我的问题
我想我已经明白为什么会发生这种情况了。这是因为之前使用了 for 循环来定义变量 tr。如果我省略这一行,那么我会得到一个带有数字和一些附加文本的数据帧。我可以通过整个 DataFrame 的循环来过滤它,但更好的方法必须是正确使用 Replace() 函数。我想不通这一点。
这是我的完整代码。我已经在一行中使用 ########################### 标记了我引用的代码的关键部分,以便可以找到该行快速(甚至按 Ctrl + F):
import requests
import pandas as pd
from bs4 import BeautifulSoup
Base_url = ("https://nseindia.com/live_market/dynaContent/"+
"live_watch/option_chain/optionKeys.jsp?symbolCode=2772&symbol=UBL&"+
"symbol=UBL&instrument=OPTSTK&date=-&segmentLink=17&segmentLink=17")
page = requests.get(Base_url)
#page.status_code
#page.content
soup = BeautifulSoup(page.content, 'html.parser')
#print(soup.prettify())
table_it = soup.find_all(class_="opttbldata")
table_cls_1 = soup.find_all(id = "octable")
col_list = []
# Pulling heading out of the Option Chain Table
#########################
for mytable in table_cls_1:
table_head = mytable.find('thead')
try:
rows = table_head.find_all('tr')
for tr in rows:
cols = tr.find_all('th')
for th in cols:
er = th.text
#########################
ee = er.encode('utf8')
col_list.append(ee)
except:
print('no thread')
col_list_fnl = [e for e in col_list if e not in ('CALLS', 'PUTS', 'Chart', '\xc2\xa0')]
#print(col_list_fnl)
table_cls_2 = soup.find(id = "octable")
all_trs = table_cls_2.find_all('tr')
req_row = table_cls_2.find_all('tr')
new_table = pd.DataFrame(index=range(0,len(req_row)-3),columns = col_list_fnl)
row_marker = 0
for row_number, tr_nos in enumerate(req_row):
if row_number <= 1 or row_number == len(req_row)-1:
continue # To insure we only choose non empty rows
td_columns = tr_nos.find_all('td')
# Removing the graph column
select_cols = td_columns[1:22]
cols_horizontal = range(0,len(select_cols))
for nu, column in enumerate(select_cols):
utf_string = column.get_text()
utf_string = utf_string.strip('\n\r\t": ')
#########################
tr = tr.replace(',' , '') # Commenting this out makes code partially work, getting numbers + text attached to the numbers in the table
# That is obtained by commenting out the above line with tr variable & running the entire code.
tr = utf_string.encode('utf8')
new_table.iloc[row_marker,[nu]] = tr
row_marker += 1
print(new_table)