2016-04-07 10 views
1

私はこのサイトのデータにアクセスしようとしています:http://surge.srcc.lsu.edu/s1.html。これまでのところ、私はドロップダウンメニューを通して自分のコードループを持っていました。そして、テーブルの上部にあるページをループしたいと思っています[1] [2] .. Selectを使用しようとしましたが、Selectがspanで使用できないというエラーが表示されます。「UnexpectedTagNameException:選択は、<スパンではない要素に対してのみ有効です」。ウェブスクラップへのページの循環

# importing libraries 
from selenium import webdriver 
import time 
from selenium.webdriver.support.ui import Select 
from bs4 import BeautifulSoup 
import re 

driver = webdriver.Firefox() 
driver.get("http://surge.srcc.lsu.edu/s1.html") 

# definition for switching frames 
def frame_switch(css_selector): 
    driver.switch_to.frame(driver.find_element_by_css_selector(css_selector)) 

# data is in an iframe 
frame_switch("iframe") 

html_source = driver.page_source 
nameSelect = Select(driver.find_element_by_xpath('//select[@id="storm_name"]')) 
stormCount = len(nameSelect.options) 
data=[] 
for i in range(1, stormCount): 
    print("starting loop on option storm " + nameSelect.options[i].text) 
    nameSelect.select_by_index(i) 
    time.sleep(3) 


    yearSelect = Select(driver.find_element_by_xpath('//select[@id="year"]')) 
    yearCount = len(yearSelect.options) 
    for j in range(1, yearCount): 
     print("starting loop on option year " + yearSelect.options[j].text) 
     yearSelect.select_by_index(j) 


     time.sleep(2) 

私はページを選択する問題が午前場所です:

 change_page=Select(driver.find_element_by_class_name("yui-pg-pages")) 
     page_count = len(change_page.options) 
     for k in range(1, page_count): 
      change_page.select_by_index(k) 



     # Select Page & run following code 
      soup = BeautifulSoup(driver.page_source, 'html.parser') 
      print(soup.find_all("tbody", {"class" : re.compile(".*")})[1]) 
      # get the needed table body 
      table=soup.find_all("tbody", {"class" : re.compile(".*")})[1] 
      rows = table.find_all('tr') 
      for row in rows: 
       cols = row.find_all('td') 
       cols = [ele.text.strip() for ele in cols] 
       data.append(cols) 
+0

は、私の答えは役に立ちましたか? – DuckPuncher

+0

はい、ありがとうございます! – Corncobpipe

+0

あなたは答えのチェックマークをクリックすることで答えを受け入れるべきです、それは本当に私を助けるでしょう:D – DuckPuncher

答えて

1

ではなく、XPathのセレクターを使用してください。

driver.find_element_by_xpath('//a[@class="yui-pg-next"]') 

次に、次のボタンとやり取りできる間にループします。私がページをループしている間にページの量が変わることがあるなら、私はこの方法を好む。 Selectを使用する必要はありません。実際、Selectはドロップダウンメニュー以外のものではないと思います。

またはページが頻繁に変更されませんので、あなたがページのリンクを使用してそれを実行する必要がある場合は、あなたが何かを試みることができる:

# Use find_elements_by_xpath to select multiple elements. 
pages = driver.find_elements_by_xpath('//a[@class="yui-pg-page"]') 

# loop through results 
for page_link in pages: 
    page_link.click() 
    # do stuff.