最初の問題:データは、フレーム内のiframeに実際にあります。 https://www.schwab.wallst.com/public/research/stocks/summary.asp?user_id=schwabpublic&symbol=APC(URLの末尾にある適切な記号で置き換えます)を調べる必要があります。
第2の問題:ページからデータを抽出する。私は個人的にlxmlとxpathが好きですが、仕事をするパッケージがたくさんあります。 - に言って、このページのマークアップは、構造、プレゼンテーションではありません。
print repr(getStockData('MSFT'))
として呼び出された場合、私はおそらくそれが
{'stock_name': 'Microsoft Corp', 'last_price': 25.690000000000001, 'stock_symbol': 'MSFT:NASDAQ'}
第三の問題点を返し
import urllib2
import lxml.html
import re
re_dollars = '\$?\s*(\d+\.\d{2})'
def urlExtractData(url, defs):
"""
Get html from url, parse according to defs, return as dictionary
defs is a list of tuples ("name", "xpath", "regex", fn)
name becomes the key in the returned dictionary
xpath is used to extract a string from the page
regex further processes the string (skipped if None)
fn casts the string to the desired type (skipped if None)
"""
page = urllib2.urlopen(url) # can modify this to include your cookies
tree = lxml.html.parse(page)
res = {}
for name,path,reg,fn in defs:
txt = tree.xpath(path)[0]
if reg != None:
match = re.search(reg,txt)
txt = match.group(1)
if fn != None:
txt = fn(txt)
res[name] = txt
return res
def getStockData(code):
url = 'https://www.schwab.wallst.com/public/research/stocks/summary.asp?user_id=schwabpublic&symbol=' + code
defs = [
("stock_name", '//span[@class="header1"]/text()', None, str),
("stock_symbol", '//span[@class="header2"]/text()', None, str),
("last_price", '//span[@class="neu"]/text()', re_dollars, float)
# etc
]
return urlExtractData(url, defs)
のようないくつかのコードを期待します私はそれに基づいてコードは、おそらく壊れやすいだろう、つまり、ページの構造(またはページ間のバリエーション)の変更は、あなたのxpathsを再加工する必要があります。
希望に役立ちます!
@hugh私はそのページからデータを取得したいと思います。次に、新しい発見スキルと他のページのコードを使用して、アイデアをありがとう。そこにはそのページに触れる方法があります。 authenationを追加し、リアルタイムデータを取得します。私は提示されたデータだけが必要です。 sybmol list 50+ ....もう一度、あなたの努力に非常に感謝します。私はそのページに触れる方法を学ぶ必要があります...... – Merlin
完全に壊れてしまったので、lxmlを使い始めました。 – Merlin
@ user428862:どのように「完全に壊れていますか?上記のコードはまだ私のために働くようです。 –