<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Selenium - イチゾーのブログ</title>
	<atom:link href="https://ichizo.biz/tag/selenium/feed" rel="self" type="application/rss+xml" />
	<link>https://ichizo.biz</link>
	<description>システム開発やWordPressについてなど</description>
	<lastBuildDate>Thu, 29 Dec 2016 08:28:39 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.1</generator>
<site xmlns="com-wordpress:feed-additions:1">120380898</site>	<item>
		<title>英語多読用の本をレベル別に取得する（完成版）</title>
		<link>https://ichizo.biz/2016/12/29/python-selenium-3.html</link>
					<comments>https://ichizo.biz/2016/12/29/python-selenium-3.html?noamp=mobile#respond</comments>
		
		<dc:creator><![CDATA[一蔵]]></dc:creator>
		<pubDate>Thu, 29 Dec 2016 03:52:31 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[英語]]></category>
		<category><![CDATA[Selenium]]></category>
		<guid isPermaLink="false">http://ichizo.biz/?p=94</guid>

					<description><![CDATA[<p>英語多読用の本をレベル別に取得する（完成版） これまでのまと [&#8230;]</p>
<p>The post <a href="https://ichizo.biz/2016/12/29/python-selenium-3.html">英語多読用の本をレベル別に取得する（完成版）</a> first appeared on <a href="https://ichizo.biz">イチゾーのブログ</a>.</p>]]></description>
										<content:encoded><![CDATA[<h2>英語多読用の本をレベル別に取得する（完成版）</h2>
<h3>これまでのまとめと残りの実装</h3>
<p>検索を行いその結果をリスト化しテキストに保存するという一連の作業を実装します。</p>
<p>検索の実行はPythonでSeleniumを動作させて行います。</p>
<p>英語多読研究会さんのWEBページから、読みやすさレベル別に本のリストを取得するスクリプトの完成版です。</p>
<p>これまで、「<a href="http://ichizo.biz/2016/12/27/python_selenium.html">英語多読用の本のリストをレベル別に取得する</a>」や<br />
「<a href="http://ichizo.biz/2016/12/28/python_selenium-2.html">英語多読用の本をレベル別に取得する（ページャーも対応）</a>」で<br />
実装してきたものの完成版です。</p>
<p>レベル別の英語多読用の本のリストをそれぞれテキストファイルに書き出すという処理です。</p>
<p>読みやすさレベルは、0.0から0.1刻みで10.0まであるので、<br />
それぞれのレベルごとに本のリストを取得して、そのISBNをテキストファイルに書き出します。</p>
<p>今までは書名を取得していたのですが、検索結果の中にISBNが含まれていたことに気が付き、これを取得することにしました。</p>
<h3>プログラムソース</h3>
<p>では、プログラムソースです。</p>
<pre class="lang:python decode:true " title="selenium_english.py" >
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 22 16:32:48 2016

@author: 
"""

from selenium import webdriver

url = 'http://www.seg.co.jp/sss_review/jsp/frm_a_100.jsp'
keyword0 = '100'
level_no = 0
isbn_list = []

def open_window():
    try:
        browser = webdriver.Chrome('./chromedriver')
    finally:
        print('END')
    return browser
        
def search_web(browser, keyword1):
    browser.get(url)
    
    search_input = browser.find_element_by_name('dt_page_in')
    search_input.send_keys(keyword0)

    search_input = browser.find_element_by_name('nm_yle')
    search_input.send_keys(keyword1)

    search_input = browser.find_element_by_name('nm_yls')
    search_input.send_keys(keyword1)
    
    browser.find_element_by_name('Submit3022233').click()
    
    return browser

def go_next_page(browser):
    isFind = True
    page_no = 1
    
    while isFind:
        get_isbns(browser)
    
        page_no += 1
        search_word = '"JavaScript:fncPagnig('+str(page_no)+');"'
        
        if browser.page_source.find(search_word) &gt; 0:
            browser.find_element_by_xpath('//a[@href='+search_word+']').click()
        else:
            isFind = False

def get_isbns(browser):
    subjects = browser.find_elements_by_class_name('subj')
    for subject in subjects:
        if subject.text.find('●ISBN：') &gt; 0:
            isbn = subject.text.split('●ISBN：')
            isbn = isbn[1].split('(')
            isbn_list.append(isbn[0])

def write_file(level_no):
    f = open('list'+str('%1.1f' % level_no)+'.txt', 'w')
    for isbn in isbn_list:
        f.write(isbn)
        f.write('\n')
    f.close()
    

if __name__ == '__main__':
    browser = open_window()
    while level_no &lt; 10:
        browser = search_web(browser, str('%1.1f' % level_no))
        go_next_page(browser)
        write_file(level_no)
        level_no += 0.1
        isbn_list = []
</pre>
<h3>プログラムソースの説明</h3>
<p>ソース下部の</p>
<pre class="lang:python decode:true " >if __name__ == '__main__':</pre>
<p>から各メソッドを実行していますので、ここから説明していきます。</p>
<p>これまではsearch_web()内で</p>
<pre class="lang:python decode:true " >browser = webdriver.Chrome('./chromedriver')</pre>
<p>を行っていたのですが、検索のたびに新しいウィンドウを立ち上げたくなかったので、<br />
別途open_window()メソッドを定義して、1回だけこれを呼び出すことにしました。</p>
<p>読みやすさレベルは、0.0から10.0まで検索を続けるので、<br />
whileループで各レベルごとに検索処理を実行します。</p>
<p>ループ内では、search_web()で検索処理を実行し、<br />
検索結果をgo_next_page()に渡します。</p>
<p>go_next_page()では、検索結果ページごとにget_isbns()を呼び出し、<br />
ページャーのリンクを探します。<br />
ページャーのリンクの数だけ、リンクをクリックし、検索結果をget_isbn()に渡すことを繰り返します。</p>
<p>get_isbns()では、ISBNはclass名が「subj」というtdタグで囲まれているので、<br />
find_elements_by_class_nameで「subj」を指定して中の文字列を取得します。<br />
これで文字列はリストに入るので、この文字列でループし、<br />
「●ISBN」という文字列がある場合だけISBNを取得し、これをリストに追加します。</p>
<p>ISBNをリストに追加し終わったらwrite_file()で<br />
読みやすさレベル別にテキストファイルに保存します。</p>
<p>次にlevel_no（読みやすさレベル）を0.1上げて、<br />
検索結果をセットするリストを初期化しておきます。</p>
<p>以上をlevel_noが10になるまで繰り返します。</p>
<p>注意事項</p>
<p>私は、非常に低スペックのパソコンで実行しているためか、<br />
Seleniumで検索を行ってページ送りしてという動作が非常に緩慢です。<br />
手動で検索を行ってページ送りしてというよりも動作が遅いぐらいです。</p>
<p>ですのでsleepを入れていませんが、<br />
高スペックパソコン等で検索やページ送りの動作が非常に速い場合は<br />
ループの間隔をあけるように適度にsleepを入れましょう。</p><p>The post <a href="https://ichizo.biz/2016/12/29/python-selenium-3.html">英語多読用の本をレベル別に取得する（完成版）</a> first appeared on <a href="https://ichizo.biz">イチゾーのブログ</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://ichizo.biz/2016/12/29/python-selenium-3.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">94</post-id>	</item>
		<item>
		<title>英語多読用の本をレベル別に取得する（ページャーも対応）</title>
		<link>https://ichizo.biz/2016/12/28/python_selenium-2.html</link>
					<comments>https://ichizo.biz/2016/12/28/python_selenium-2.html?noamp=mobile#respond</comments>
		
		<dc:creator><![CDATA[一蔵]]></dc:creator>
		<pubDate>Wed, 28 Dec 2016 08:04:19 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[英語]]></category>
		<category><![CDATA[Selenium]]></category>
		<guid isPermaLink="false">http://ichizo.biz/?p=91</guid>

					<description><![CDATA[<p>英語多読用の本をレベル別に取得する（ページャーに対応する）  [&#8230;]</p>
<p>The post <a href="https://ichizo.biz/2016/12/28/python_selenium-2.html">英語多読用の本をレベル別に取得する（ページャーも対応）</a> first appeared on <a href="https://ichizo.biz">イチゾーのブログ</a>.</p>]]></description>
										<content:encoded><![CDATA[<h2>英語多読用の本をレベル別に取得する（ページャーに対応する）</h2>
<p>前回の「<a href="http://ichizo.biz/2016/12/27/python_selenium.html">英語多読用の本のリストをレベル別に取得する</a>」に引き続き、<br />
英語多読研究会さんのデータベースから、読みやすさレベル別の書籍リストを取得する実装を行います。</p>
<p>検索結果が多数のページにまたがらないように、結果一覧ページの表示件数を最大の100件にしています。<br />
また読みやすさレベルで細かく分けられるように、検索項目の読みやすさレベルを0.1刻みで上げていく方法を取ります。<br />
他の絞り込み条件を入れると、リストから漏れてしまったりということも考えられなくもないので、<br />
単純に読みやすさレベルを細かく刻むことでその対応とします。</p>
<p>前回の記事で紹介したPythonのソースをさらに書き換えます。</p>
<p>プログラムは以下のようになりました。</p>
<h3>プログラムソース</h3>
<pre class="lang:python decode:true " title="get Book List" >
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 22 16:32:48 2016

@author: 
"""

from selenium import webdriver

url = 'http://www.seg.co.jp/sss_review/jsp/frm_a_100.jsp'
keyword0 = '100'
keyword1 = '0.0'
keyword2 = '0.0'
title_list = []

def search_web():
    try:
        browser = webdriver.Chrome('./chromedriver')
        browser.get(url)
        
        search_input = browser.find_element_by_name('dt_page_in')
        search_input.send_keys(keyword0)

        search_input = browser.find_element_by_name('nm_yle')
        search_input.send_keys(keyword1)

        search_input = browser.find_element_by_name('nm_yls')
        search_input.send_keys(keyword2)
        
        browser.find_element_by_name('Submit3022233').click()
        
        get_titles(browser)

        page_no = 2

        search_word = '"JavaScript:fncPagnig('+str(page_no)+');"'
        page_source = browser.page_source
        while page_source.find(search_word) &gt; 0:
            browser.find_element_by_xpath('//a[@href='+search_word+']').click()
            get_titles(browser)
            page_no += 1
            search_word = '"JavaScript:fncPagnig('+str(page_no)+');"'
            
    finally:
        print('END')

    return title_list

def get_titles(page_text):
    titles = page_text.find_elements_by_xpath('//b')
    isTitle = 0
    for title in titles:
        if isTitle == 0 and title.text == '簡易検索：':
            isTitle = 1
        elif isTitle == 1 and title.text == 'ISBN検索：':
            isTitle = 2
        elif isTitle == 1:
            #print(title.text)
            title_list.append(title.text)

            
if __name__ == '__main__':
    search_web()
    print(title_list)
</pre>
<h3>プログラムソースの内容</h3>
<p>今回は、プログラムの冒頭で、以下のように空のリスト「title_list」を宣言します。</p>
<pre class="lang:python decode:true " >
title_list = []
</pre>
<p>search_web()で英語多読研究会さんのサイトからデータの取得処理を行います。</p>
<pre class="lang:python decode:true " >
browser = webdriver.Chrome('./chromedriver')
</pre>
<p>で、chromedriverを立ち上げて、send_keysで検索項目を指定し、<br />
下記のclick()で検索処理を実行するところまでは前回と同じです。</p>
<pre class="lang:python decode:true " >
browser.find_element_by_name('Submit3022233').click()
</pre>
<p>その後、以下でget_titles()を実行します。</p>
<pre class="lang:python decode:true " >
get_titles(browser)
</pre>
<p>取得した書名リストをtitle_listに追加します。</p>
<pre class="lang:python decode:true " >
title_list.append(title.text)
</pre>
<p>ここまで終わると、再びsearch_web()に戻ります。</p>
<p>ページャーのリンクは、以下のタグです。</p>
<pre class="lang:python decode:true " >
&lt;a href="JavaScript:fncPagnig(2);" style="color=blue;"&gt;2&lt;/a&gt;
</pre>
<p>これをクリックすることで2ページ目に遷移します。</p>
<p>ページャーがあると、&#8221;JavaScript:fncPagnig(2);&#8221; という文字列がページソース内に存在します。<br />
最初に page_no = 2 として、以下のようにsearch_wordという文字列を生成します。</p>
<pre class="lang:python decode:true " >
search_word = '"JavaScript:fncPagnig('+str(page_no)+');"'
</pre>
<p>3ページ以上あることも想定して、page_no をインクリメントし、<br />
その値で生成したsearch_wordで、ページソースを検索します。</p>
<pre class="lang:python decode:true " >
while page_source.find(search_word) &amp;gt; 0:
</pre>
<p>ページソース内にページャーがあった場合はwhileループ内を実行します。</p>
<p>まずは、以下でページャーのリンクをクリックします。</p>
<pre class="lang:python decode:true " >
browser.find_element_by_xpath('//a[@href='+search_word+']').click()
</pre>
<pre class="lang:python decode:true " >
get_titles(browser)
</pre>
<p>で検索結果ページから書名リストを取得します。</p>
<pre class="lang:python decode:true " >
page_no += 1
search_word = '"JavaScript:fncPagnig('+str(page_no)+');"'
</pre>
<p>でpage_noをインクリメントして、その値でリンク先の文字列を生成します。</p>
<p>while文で、この値（次のページのリンク）が存在するかを調べ、<br />
存在する場合は再度ループ内を実行します。</p>
<p>次ページが存在しない場合は、ループを抜けてプログラムを終了します。</p>
<p>次は、書名のリストをテキストファイルに書き出すことと、<br />
これまで固定だった検索項目（読みやすさレベル）を動かして<br />
それぞれの読みやすさレベルごとに書名リストのテキストファイルを<br />
生成することを実装したいと思います。</p><p>The post <a href="https://ichizo.biz/2016/12/28/python_selenium-2.html">英語多読用の本をレベル別に取得する（ページャーも対応）</a> first appeared on <a href="https://ichizo.biz">イチゾーのブログ</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://ichizo.biz/2016/12/28/python_selenium-2.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">91</post-id>	</item>
		<item>
		<title>英語多読用の本のリストをレベル別に取得する</title>
		<link>https://ichizo.biz/2016/12/27/python_selenium.html</link>
					<comments>https://ichizo.biz/2016/12/27/python_selenium.html?noamp=mobile#respond</comments>
		
		<dc:creator><![CDATA[一蔵]]></dc:creator>
		<pubDate>Tue, 27 Dec 2016 07:55:05 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[英語]]></category>
		<category><![CDATA[Selenium]]></category>
		<guid isPermaLink="false">http://ichizo.biz/?p=88</guid>

					<description><![CDATA[<p>英語多読用の本のリストをレベル別に取得したい 英語多読研究会 [&#8230;]</p>
<p>The post <a href="https://ichizo.biz/2016/12/27/python_selenium.html">英語多読用の本のリストをレベル別に取得する</a> first appeared on <a href="https://ichizo.biz">イチゾーのブログ</a>.</p>]]></description>
										<content:encoded><![CDATA[<h2>英語多読用の本のリストをレベル別に取得したい</h2>
<p>英語多読研究会さんが、<a href="http://www.seg.co.jp/sss_review/jsp/frm_a_100.jsp" target="_blank">英語多読に使える本のデータベース</a>を公開してくれています。<br />
読みやすさレベルを指定して検索することができるので、<br />
自分のレベルに合わせた本を探すのに非常に使い勝手がいいサイトになっています。</p>
<p>このリストから読みたい本を見つけて英語多読に役立てたいところですが、<br />
個別に本を買っていると結構お金がかかってしまいます。</p>
<p>そこで洋書も多いKindle Unlimitedで対象の本があれば<br />
月額980円で読み放題ということで、<br />
より英語多読がやりやすくなります。</p>
<p>ということで、英語多読に役立てたいという目的で、<br />
英語多読研究会さんのデータベースからレベル別に<br />
本のリストを取得することを考えてみます。</p>
<h3>Seleniumを使おう</h3>
<p>レベル別に英語本のリストを取得するには、<br />
検索画面に抽出したいレベルを指定して<br />
検索要求を投げる必要があります。</p>
<p>最初はPythonスクリプトからRequestsを使って<br />
リスト取得することを考えました。</p>
<p>検索項目等の指定をした上で検索要求を投げる訳ですが、<br />
再び検索画面が表示されるだけで、なぜか検索結果画面が表示されません。<br />
（検索画面と検索結果画面のURLが同じで、どうにも受け渡しているパラメーターによって切り替えているっぽいです）</p>
<p>Requestsでヘッダ情報をセットしたり、<br />
検索画面で受け取ったクッキーを検索要求で渡すなどやってみましたが<br />
うまくいかずRequestsでの検索要求はやめることにしました。<br />
（ブラウザから渡しているhidden項目等を渡してみましたがことごとくダメでした）</p>
<p>ということでSeleniumでブラウザを操作して検索結果を取得してみます。</p>
<h3>Seleniumを操作するプログラム</h3>
<p>まずはプログラムソースを。</p>
<p>前回の記事「<a href="http://ichizo.biz/2016/12/22/python-selenium.html">PythonとSeleniumでブラウザの自動操作</a>」で作成したソースを改変します。</p>
<pre class="lang:python decode:true " title="selenium_english.py" >
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 22 16:32:48 2016

@author: 
"""

from selenium import webdriver

url = 'http://www.seg.co.jp/sss_review/jsp/frm_a_100.jsp'
keyword0 = '100'
keyword1 = '0.0'
keyword2 = '0.0'


def search_web():
    try:
        browser = webdriver.Chrome('./chromedriver')
        browser.get(url)
        
        search_input = browser.find_element_by_name('dt_page_in')
        search_input.send_keys(keyword0)

        search_input = browser.find_element_by_name('nm_yle')
        search_input.send_keys(keyword1)

        search_input = browser.find_element_by_name('nm_yls')
        search_input.send_keys(keyword2)
        
        browser.find_element_by_name('Submit3022233').click()
        
        #print(browser.page_source)
        titles = browser.find_elements_by_xpath('//b')
        isTitle = 0
        for title in titles:
            if isTitle == 0 and title.text == '簡易検索：':
                isTitle = 1
            elif isTitle == 1 and title.text == 'ISBN検索：':
                isTitle = 2
            elif isTitle == 1:
                print(title.text)
            #booktext = bookdata.text

        
    finally:
        print('END')


if __name__ == '__main__':
    search_web()
</pre>
<h3>プログラムソースの解説</h3>
<p>keyword0 = &#8216;100&#8217;で、表示件数（100件）、<br />
keyword1 = &#8216;0.0&#8217;とkeyword2 = &#8216;0.0&#8217;で読みやすさレベルを設定しておきます。</p>
<pre class="lang:python decode:true " >
browser = webdriver.Chrome('./chromedriver') 
</pre>
<p>で、Pythonスクリプトと同じディレクトリ内に置いたchrmedriverを読み込みます。<br />
browser.get(url) で指定したURLを開きます。</p>
<pre class="lang:python decode:true " >
search_input = browser.find_element_by_name('dt_page_in')
search_input.send_keys(keyword0)
</pre>
<p>で、dt_page_inにkeyword0（100）をセットします。</p>
<p>同様に「nm_yle」と「nm_yls」に検索項目である読みやすさレベルを指定します。</p>
<pre class="lang:python decode:true " >
browser.find_element_by_name('Submit3022233').click()
</pre>
<p>で検索ボックスをクリックします。</p>
<p>検索結果ページはbrowserに入っていて、<br />
書名は「bタグ」で囲まれているので、書名リストをfind_elements_by_xpathで取得します。</p>
<pre class="lang:python decode:true " >
titles = browser.find_elements_by_xpath('//b')
</pre>
<p>titlesにbタグで囲まれた書名のリストが入っていますが、<br />
それ以外のbタグで囲まれた部分もリストに入っているので、<br />
以下で取り除きます。</p>
<pre class="lang:python decode:true " >
isTitle = 0
for title in titles:
    if isTitle == 0 and title.text == '簡易検索：':
        isTitle = 1
    elif isTitle == 1 and title.text == 'ISBN検索：':
        isTitle = 2
    elif isTitle == 1:
        print(title.text)
</pre>
<p>ここまでで、検索を実行して表示された検索結果ページから<br />
書名のリストを取得する（ただし最初の1ページ目のみ）ということができました。</p>
<p>引き続いて次回は、検索結果が複数ページに渡る場合に<br />
画面を遷移させた上で書名リストを取得し、<br />
これをテキストファイルに出力するということを行います。</p>
<p>Pythonって直観的で使いやすい言語ですね。</p><p>The post <a href="https://ichizo.biz/2016/12/27/python_selenium.html">英語多読用の本のリストをレベル別に取得する</a> first appeared on <a href="https://ichizo.biz">イチゾーのブログ</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://ichizo.biz/2016/12/27/python_selenium.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">88</post-id>	</item>
		<item>
		<title>PythonとSeleniumでブラウザの自動操作</title>
		<link>https://ichizo.biz/2016/12/22/python-selenium.html</link>
					<comments>https://ichizo.biz/2016/12/22/python-selenium.html?noamp=mobile#respond</comments>
		
		<dc:creator><![CDATA[一蔵]]></dc:creator>
		<pubDate>Thu, 22 Dec 2016 07:55:43 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Selenium]]></category>
		<guid isPermaLink="false">http://ichizo.biz/?p=81</guid>

					<description><![CDATA[<p>PythonとSeleniumでブラウザの自動操作 今回は、 [&#8230;]</p>
<p>The post <a href="https://ichizo.biz/2016/12/22/python-selenium.html">PythonとSeleniumでブラウザの自動操作</a> first appeared on <a href="https://ichizo.biz">イチゾーのブログ</a>.</p>]]></description>
										<content:encoded><![CDATA[<h2>PythonとSeleniumでブラウザの自動操作</h2>
<p>今回は、PythonからSeleniumを動かしてブラウザの自動操作をやってみます。</p>
<p>前回の「<a href="http://ichizo.biz/2016/12/22/python-search.html">PythonのRequestsを使って検索結果を取得する</a>」で、<br />
うまく検索結果を取得できなかったサイトがあったので<br />
今回はSeleniumを使用してみます。</p>
<p>Requestsで取得できなかったのは、見えないところで何らかのパラメーターを渡しているのか、<br />
header情報が必要なのか、画面表示の際にJavaScriptが動いているようなので<br />
これが何かをやっているのか等々なのですが、<br />
ブラウザ操作からは簡単に結果を取得できるので<br />
Requestsは早々に諦めてSeleniumを使ってみることにしました。</p>
<h3>Seleniumとは？</h3>
<p>ブラウザの自動操作ツールです。</p>
<p>Pythonから操作できるということで、Python勉強中の私は<br />
勉強も兼ねてSeleniumを使ってみたいと思います。</p>
<p>まずはSeleniumのインストールです。</p>
<p>これはpipから行えます。</p>
<p>私はWindows環境なので、コマンドプロンプトを管理者権限で立ち上げて<br />
以下のコマンドを実行します。</p>
<pre class="lang:python decode:true " title="install selenium" >
pip install selenium
</pre>
<p>すると以下のようにインストールされます。</p>
<pre class="lang:batch decode:true " title="install selenium" >
Collecting selenium
  Downloading selenium-3.0.2-py2.py3-none-any.whl (915kB)
    100% |################################| 921kB 359kB/s
Installing collected packages: selenium
Successfully installed selenium-3.0.2
</pre>
<p>ブラウザはChromeを使いたいのですが、<br />
ドライバが必要なようです。</p>
<p>ChromeDriverを<a href="https://sites.google.com/a/chromium.org/chromedriver/downloads" target="_blank">ダウンロードサイト</a>からダウンロードします。</p>
<p>「Latest Release:」の後ろの「ChromeDriver 2.26」（2016/12/22現在）の<br />
リンクをクリックするとファイル一覧が表示されます。</p>
<p>「chromedriver_win32.zip」をダウンロードします。</p>
<p>解凍すると「chromedriver.exe」というファイルが現れるので、<br />
これをPythonファイルと同じフォルダ内に移動します。</p>
<h3>Pythonのプログラムを実装</h3>
<pre class="lang:python decode:true " title="searchy.py" >
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 22 16:32:48 2016

@author: 
"""

import time
from selenium import webdriver

url = 'http://search.yahoo.co.jp/search'
keyword = 'python'

def search_web():
    try:
        browser = webdriver.Chrome('./chromedriver')
        browser.get(url)
        time.sleep(1)
        
        search_input = browser.find_element_by_name('p')
        search_input.send_keys(keyword)
        search_input.submit()
        time.sleep(1)
        
        print(browser.page_source)
        
    finally:
        print('END')


if __name__ == '__main__':
    search_web()
</pre>
<p>seleniumのwebdriverを使用するために、「from selenium import webdriver」を宣言します。</p>
<p>対象ページのURLと検索キーワードを設定しておきます。</p>
<p>search_web()内では、「webdriver.Chrome(&#8216;./chromedriver&#8217;)」で<br />
同じディレクトリ内にあるchromedriverを起動します。</p>
<p>「browser.get(url)」でブラウザにURLを渡します。</p>
<p>検索キーワードの入力ボックスのnameが「p」だったので、<br />
「search_input = browser.find_element_by_name(&#8216;p&#8217;)」として指定します。</p>
<p>「search_input.send_keys(keyword)」でキーワードをセットします。</p>
<p>「search_input.submit()」で検索を実行します。</p>
<p>検索結果は「browser.page_source」から取得します。</p>
<p>実際に実行してみると、まずchromedriverが起動し、<br />
次にChromeが立ち上がります。</p>
<p>http://search.yahoo.co.jp/searchに移動し、<br />
検索ボックスに「python」が入力されます。</p>
<p>さらに検索が実行され、検索結果ページが表示されました。</p>
<p>最後にChromeが閉じ、検索結果ページのソースが出力されました。</p>
<p>これだけ簡単な操作だと、実装コードも少なくて簡単ですね。</p>
<p>ちなみに、「検索」ボタンがsubmitではなくて、<br />
onclickでJavasScriptを実行している場合は、<br />
「search_input.submit()」の部分を下記で置き換えます。</p>
<pre class="lang:python decode:true " >
browser.find_element_by_name('Search').click()
</pre><p>The post <a href="https://ichizo.biz/2016/12/22/python-selenium.html">PythonとSeleniumでブラウザの自動操作</a> first appeared on <a href="https://ichizo.biz">イチゾーのブログ</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://ichizo.biz/2016/12/22/python-selenium.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">81</post-id>	</item>
	</channel>
</rss>
