phantomjs を適切にストップするには

phantomjsは便利なんだけど、プロセスが何故かゾンビ化してリソースを圧迫するなんてことがあります。
python + selenium + phantomjsで運用していますが、
大抵は、dirver.close()、dirver.quit()でスットプできますが、たまに生き残ります。

pgrep phantomjs | xargs kill

シェル側からphangomjsを強制的にkillしてしまうのが確実で、これをpython スクリプトに仕込んどけばOKです。
ただし副作用もあって、これだと他のすべてのphantomjsをkillしちゃうので、人を選ぶわけです。

import signal

driver.service.process.send_signal(signal.SIGTERM) # kill the specific phantomjs child proc
driver.quit()                                      # quit the node proc

といのが良いのかなという感じみたいです。

サーバーにphantomjsをおいてスクレイピングを動かしたい時

サーバーにphantomjsを置くなら、npmからインストールするのがおすすめ

sudo yum install epel-release
sudo yum install nodejs npm

でnpmをインストールして

npm install phantomjs

でphantomjsをインストールする。
node_modulesというフォルダができてその中にphantomjsがインストールされるのでそこにパスを張る。
実際のインスコ先は
node_modules/phantomjs/bin/phantomjs
になる。

from selenium import webdriver
import time
from bs4 import BeautifulSoup

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 "
    "(KHTML, like Gecko) Chrome/15.0.87"
)

driver = webdriver.PhantomJS("/home/user/app/node_modules/phantomjs/bin/phantomjs", desired_capabilities=dcap)

url="http://yahoo.co.jp" #yahooは単なるたとえ
driver.get(url)

#スクリーンショットのとり方
driver.save_screenshot("./screen_shot_1.png")

# javascriptのレンダリングを確実に待つ、読み込み待機 time.sleep(5)とか使ってもいいけど、下記の方が確実でいい。
#例外処理をちゃんと書くともっと良い
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "articleList")))

#BeautifulSoupで欲しい部分を
soup = BeautifulSoup(driver.page_source,'html.parser')

#h2要素でclassがarticleList__titleのものを引っ張ってくる。
h2_element = soup.find_all("h2", class_="articleList__title")

#h2要素内からa要素を探してきて、href(リンク)とaタグに囲まれている文字列を抜き出す。
for article in h2_element:
        print(article.find("a").get("href"))
   print(article.find("a").string)

pythonでプログラム実行前にミスをチェックする

ちょっとだけ変更したプログラムで、ミスタイプや、ちょっとしたミスを事前にチェックしたいときには、

python -m py_compile [自分のプログラム].py

コンパイルしちゃいましょう。
しょうも無いミスを発見してくれます。

scpで嵌まるなど

scpが突然できなくなった。
sshで入ることはできるのに、ファイルを送ることができなくなった。

scl enable devtoolset-2 bash
.cshrcファイルに最近加えたのが問題だったらしい。

scpが使えなくなったら設定ファイルに何か最近加えてないか考えると良い。

参考サイト

unix.stackexchange.com

fftwのインストール

高速フーリエ変換のライブラリであるfftwであるが、
fortranのプログラムをコンパイルするのにfftw3.hなるヘッダが必要になる。

yum -y install fftw ではfftw3.hがインストールされないので

yum -y install fftw fftw-develとfftw-develも入れてやる必要がある。
はまったやんか

6485 前澤給装工業

平成29年3月期 第1四半期決算短信より

現金 112億
手形 55億
電子記録債権 33億
有価証券 2億
投資有価証券 20億

負債 68億

ネットネット資産 112+55+33+2+20−68= 154億円

時価総額 168億円

実質 14億円
平均的に見て12億ぐらいの純利益をだしている。
最も悪い2011年3月期にも9.5億の純利益。

事業は水道用給水装置シェア4割と地味で、成長性はあんまりなさそうだけど、安いのでのんびり持てばむくわれそう。