2017-06-16 4 views
-1

6000株のWebからプログラムでデータを収集しようとしていましたが、Python 3.6 selenium webdriver Firefoxを使用しました。 [BeautifulSoupを使用してHTMLを解析しようとしましたが、Webを更新するたびにリンクが変わらず、スープがJavaScriptに対応していないようです]Python webscrapingはループに失敗しますが、手動で行うと動作します

とにかくforループを作成するとこれは、コード内の特定の行、share_price = driver.find_element_by_css_selector(".highcharts-root > g:nth-child(25) > text:nth-child(2)")がほとんど間違っている(それは数回働いたので、私は自分のコードが良いと信じています)。しかし、手動で(Python IDLEにコピーアンドペーストして実行すると)うまく動作します。私はtime.sleep(4)を使用して、バックグラウンドから何かを救済する前にWebをロードできるようにしようとしましたが、これは解決策ではないようです。今私はヒントを使い果たしている。誰も私を助けることができるこれを解明する。以下は

は私のコードです:

from selenium import webdriver 
import time 
import pyautogui 
filename = "historical_price_marketcap.csv" 
f = open(filename,"w") 
headers = "stock_ticker, share_price, market_cap\n" 
f.write(headers) 
driver = webdriver.Firefox() 
def get_web(): 
    driver.get("https://stockrow.com") 
import csv 
with open("TICKER.csv") as file: 
     read = csv.reader(file) 
     TICKER=[] 
     for row in read: 
       ticker = row[0][1:-1] 
       TICKER.append(ticker) 
for Ticker in range(len(TICKER)): 
    get_web() 
    time.sleep(3) 
    pyautogui.click(425, 337) 
    pyautogui.typewrite(TICKER[Ticker],0.25) 
    time.sleep(2) 
    pyautogui.press("enter") 
    time.sleep(2) 
    pyautogui.click(268, 337) 
    pyautogui.press("backspace") 
    time.sleep(2) 
    pyautogui.typewrite('Stock Price',0.25) 
    time.sleep(2) 
    pyautogui.press("enter") 
    time.sleep(2) 

    pyautogui.click(702, 427) 
    for i in range(int(10)): 
      pyautogui.press("backspace") 
    time.sleep(2) 
    pyautogui.typewrite("2013-12-01",0.25) 
    pyautogui.press("enter") 
    time.sleep(2) 

    pyautogui.click(882, 425) 
    for k in range(10): 
      pyautogui.press("backspace") 
    time.sleep(2) 
    pyautogui.typewrite("2013-12-31",0.25) 
    pyautogui.press("enter") 
    time.sleep(2) 

    pyautogui.click(1317, 318) 
    for j in range(3): 
      pyautogui.press("down") 

    time.sleep(10) 
    share_price = driver.find_element_by_css_selector(".highcharts-root > g:nth-child(25) > text:nth-child(2)") 
    get_web() 
    time.sleep(3) 
    pyautogui.click(425, 337) 
    pyautogui.typewrite(TICKER[Ticker],0.25) 
    time.sleep(2) 
    pyautogui.press("enter") 
    time.sleep(2) 
    pyautogui.click(268, 337) 
    pyautogui.press("backspace") 
    time.sleep(2) 
    pyautogui.typewrite('Market Cap',0.25) 
    time.sleep(2) 
    pyautogui.press("enter") 
    time.sleep(2) 

    pyautogui.click(702, 427) 
    for i in range(int(10)): 
      pyautogui.press("backspace") 
    time.sleep(2) 
    pyautogui.typewrite("2013-12-01",0.25) 
    pyautogui.press("enter") 
    time.sleep(2) 

    pyautogui.click(882, 425) 
    for k in range(10): 
      pyautogui.press("backspace") 
    time.sleep(2) 
    pyautogui.typewrite("2013-12-31",0.25) 
    pyautogui.press("enter") 
    time.sleep(2) 

    pyautogui.click(1317, 318) 
    for j in range(3): 
      pyautogui.press("down") 

    time.sleep(10) 
    market_cap = driver.find_element_by_css_selector(".highcharts-root > g:nth-child(28) > text:nth-child(2)") 
f.close() 

私を悩ませている2行はここshare_price = driver.find_element_by_css_selector(".highcharts-root > g:nth-child(25) > text:nth-child(2)")ようですパイソンからのエラーメッセージである:それはほとんどの動作しません

Traceback (most recent call last): 
    File "C:\Users\HENGBIN\Desktop\get_historical_data.py", line 65, in <module> 
    share_price = driver.find_element_by_css_selector(".highcharts-root > g:nth-child(25) > text:nth-child(2)") 
    File "E:\Program Files\python3.6.1\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 457, in find_element_by_css_selector 
    return self.find_element(by=By.CSS_SELECTOR, value=css_selector) 
    File "E:\Program Files\python3.6.1\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 791, in find_element 
    'value': value})['value'] 
    File "E:\Program Files\python3.6.1\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 256, in execute 
    self.error_handler.check_response(response) 
    File "E:\Program Files\python3.6.1\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response 
    raise exception_class(message, screen, stacktrace) 
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .highcharts-root > g:nth-child(25) > text:nth-child(2) 

ループ内の時間ですが、Python IDLEで手動で実行するとうまく動作します。私は何が起こっているのかわかりません.........

答えて

0

あなたのスクリプトには、私は異なったやり方がいくつかあります。 まず最初に、pyautoguiを取り除こうとします。 Seleniumは、クリックして(チェックアウトthis SO-question)、あらゆる種類のキーを送信するための機能を組み込んでいます(this SO-questionをチェックしてください)。また、ブラウザで(pyautoguiで)コンテンツを変更すると、セレンは常にこれらの変更を認識するわけではありません。それはセレンでそれらを検索するときにpyautoguiが作成した要素を見つけることに関する問題を説明することができます。

第2に:get_web()関数が問題を引き起こす可能性があります。一般的に言えば、関数内のコンテンツは、関数の外部からアクセス可能になるように返されなければならず、グローバルに宣言されなければなりません。あなたのウェブページを開くドライバは、グローバル(関数外でインスタンス化します)ですが、関数内のURLはローカルであり、関数外のコンテンツにアクセスする際に問題が発生する可能性があります。私は(それは本当にURLを開く以外に何もしないよう)あなたが機能を取り除くことをお勧めしますと、単純にそのようなあなたのコード内の関数呼び出しを置き換えたい:これは、それを可能にする必要があります

for Ticker in range(len(TICKER)): 
    driver.get("https://stockrow.com") 
    time.sleep(3) 
    # insert keys, click and so on... 

あなたはseleniums driver.find_elements ...-メソッドを使用することができます。

第3に、サイトからいくつかのデータを抽出するとします。そうであれば、セレン以外の何かで構文解析を行います。セレンは遅いパーサーです。代わりにBeautifulSoupを試すことができます。 (それはあなたがそれについて移動する方法を紹介しますがSO-question here、)

サイトはあなたが欲しいものは何でもBeautifulSoupでHTMLやエキスを読み込むロードされると

from bs4 import BeautifulSoup 
..... 
html = driver.page_source 
soup = BeautifulSoup(html, "html.parser") 
element_you_want_to_retrieve = soup.find('tag_name', attrs={'key': 'value'}) 
+0

beautifulsoupおそらくウェブとしては良い選択ではありません。

url = 'https://stockrow.com/api/fundamentals.json?indicators[]=0&tickers[]=APPL' 

そうは次のようにそう要求するライブラリを使用すると、JSONなどのコンテンツを取得することができJavaScriptを使用しています。 –

0

が、このサイトで何を本当にそのサイトが独自に行うAPIコールを利用する必要があります。 Chromesインスペクタツールを使用します。あなたは、それが直接呼び出すことができ、セレンの全体を避けることができる3つのAPIを照会することがわかります。

リンゴのURLは次のようになります。

import requests 
from pprint import pprint 
url = 'https://stockrow.com/api/fundamentals.json?indicators[]=0&tickers[]=AAPL' 
response = requests.get(url).json() 
pprint(response) 
+0

ありがとう、それは良いようです! –

+0

クール。質問に回答したようにマークしてください。他の人が時間を無駄にしないようにしてください。 – jlaur

関連する問題