Как получить данные из таблицы HTML в формате сетки в Python - PullRequest
0 голосов
/ 06 мая 2019

Я пытаюсь получить таблицу с веб-страницы биржи, чтобы поиграть с ней. В идеале ищет какую-то переменную Matrix (dataframe ??), чтобы с ней было легко играть. Тем не менее, до сих пор я застрял с разбором самой HTML-таблицы. Вот код ....

from lxml import etree
from urllib.request import Request, urlopen
import requests

SYMBOL = "NIFTY"

URL = "https://www.nseindia.com/live_market/dynaContent/live_watch  /option_chain/optionKeys.jsp?symbol=" + SYMBOL + "&date=-"
headers =  {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

req =Request(url=URL, headers=headers)
Opt_Page = urlopen(req).read()
#print(Opt_Page)
html = etree.HTML(Opt_Page)

tr_nodes = html.xpath('//table[@id="octable"]/tr')
tmp = tr_nodes[0].xpath("th") #herein begins the problem.
# this give totally blank output.. tried with node[0] to [20]
print(tmp) 

## 'th' is inside first 'tr'
header = [i[1].text for i in tr_nodes[1].xpath("th")]
td_content = [[td.text for td in tr.xpath('td')] for tr in tr_nodes[1:]]

print(header)     # all headers are empty
print(td_content) # all content is empty

ожидаем, что заголовки строк и содержимое отдельных строк будут выводиться ...

1 Ответ

0 голосов
/ 06 мая 2019

Вы можете установить библиотеку pandas pip install pandas, а также соответствующие зависимости (вероятно, pip install lxml), а затем использовать DataFrame:

from pandas import read_html

html = """
<table>
  <tr>
    <th>First</th>
    <th>Last</th>
  </tr>
  <tr>
    <td>John</td>
    <td>Smith</td>
  </tr>
  <tr>
    <td>Jane</td>
    <td>Doe</td>
  </tr>
</table>
"""
tables = read_html(html)
df = tables[0]

print(df)
print('----------')
print(df['Last'][0])

# Prints the following:
# 
#   First   Last
# 0  John  Smith
# 1  Jane    Doe
# ----------
# Smith

Для получения дополнительной помощи по использованию панд DataFrame s, посмотрите учебник здесь или официальную документацию здесь .

...