ラベル Python の投稿を表示しています。 すべての投稿を表示
ラベル Python の投稿を表示しています。 すべての投稿を表示

2022年5月13日金曜日

Python3 「urlopen error [SSL: CERTIFICATE_VERIFY_FAILED]」エラーの解決方法

 結論から言うと、以下のコマンドを実行すればエラーが解消されます

/Applications/Python\ 3.10/Install\ Certificates.command

2019年9月26日木曜日

centos6.7にpython3.6のインストール方法

centos6にディフォルトpython2.6がインストールされている状態ですが、python3系を使いたいので、早速インストールしてみます。

まず、iusリポジトリーが有効にします。

# yum install -y https://centos6.iuscommunity.org/ius-release.rpm
Loaded plugins: fastestmirror, security
Setting up Install Process
Cannot open: https://centos6.iuscommunity.org/ius-release.rpm. Skipping.
Error: Nothing to do

理由はよくわからないですが、リポジトリーを足せなかったです。
むりやり、rpmファイルを落としてきます。
# wget https://centos6.iuscommunity.org/ius-release.rpm
rpmでインストールします。
# rpm -ivh ius-release.rpm
インストールできたことを確認します。
# yum repolist all | grep 'ius'
ius                    IUS for Enterprise Linux 6 - x86_64        enabled:   244
ius-archive            IUS for Enterprise Linux 6 - Archive - x86 disabled
ius-archive-debuginfo  IUS for Enterprise Linux 6 - Archive - x86 disabled
ius-archive-source     IUS for Enterprise Linux 6 - Archive - Sou disabled
ius-debuginfo          IUS for Enterprise Linux 6 - x86_64 - Debu disabled
ius-source             IUS for Enterprise Linux 6 - Source        disabled
ius-testing            IUS for Enterprise Linux 6 - Testing - x86 disabled
ius-testing-debuginfo  IUS for Enterprise Linux 6 - Testing - x86 disabled

ius-testing-source     IUS for Enterprise Linux 6 - Testing - Sou disabled

Python3.6をインストールします。

インストール可能なパッケージがあるかを確認
# yum --enablerepo=ius search python36
Loaded plugins: fastestmirror, security
Loading mirror speeds from cached hostfile
 * base: ftp-srv2.kddilabs.jp
 * extras: ftp-srv2.kddilabs.jp
 * updates: ftp-srv2.kddilabs.jp
============================================================================== N/S Matched: python36 ===============================================================================
python36u-test.x86_64 : The self-test suite for the main python36u package
python36.x86_64 : Interpreter of the Python programming language
python36-debug.x86_64 : Debug version of the Python runtime
python36-devel.x86_64 : Libraries and header files needed for Python development
python36-gunicorn.noarch : Python WSGI application server
python36-idle.x86_64 : A basic graphical development environment for Python
python36-libs.x86_64 : Python runtime libraries
python36-lxml.x86_64 : XML processing library combining libxml2/libxslt with the ElementTree API
python36-mod_wsgi.x86_64 : A WSGI interface for Python web applications in Apache
python36-pip.noarch : A tool for installing and managing Python packages
python36-redis.noarch : Python interface to the Redis key-value store
python36-setproctitle.x86_64 : Python module to customize a process title
python36-setuptools.noarch : Easily build and distribute Python packages
python36-test.x86_64 : The self-test suite for the main python3 package
python36-tkinter.x86_64 : A GUI toolkit for Python
python36u.x86_64 : Interpreter of the Python programming language
python36u-debug.x86_64 : Debug version of the Python runtime
python36u-devel.x86_64 : Libraries and header files needed for Python development
python36u-gunicorn.noarch : Python WSGI application server
python36u-libs.x86_64 : Python runtime libraries
python36u-lxml.x86_64 : XML processing library combining libxml2/libxslt with the ElementTree API
python36u-mod_wsgi.x86_64 : A WSGI interface for Python web applications in Apache
python36u-pip.noarch : A tool for installing and managing Python packages
python36u-redis.noarch : Python interface to the Redis key-value store
python36u-setproctitle.x86_64 : Python module to customize a process title
python36u-setuptools.noarch : Easily build and distribute Python packages
python36u-tkinter.x86_64 : A GUI toolkit for Python
python36u-tools.x86_64 : A collection of tools included with Python including 2to3 and idle
uwsgi-plugin-python36u.x86_64 : uWSGI - Plugin for Python support
いよいよインストールします。
# yum --enablerepo=ius install python36
インストールできたことを確認
# python36 --version
Python 3.6.8

2019年9月17日火曜日

Pythonでselenium 要素の存在を判定する方法

Seleniumで存在しない要素を使うと、Message: Unable to locate element:xxx のエラーが起きます。
事前に要素の存在をチェックしておきたいですね。

たまに以下のようなtryで例外処理をする方法をみかけますが、実はlenでも判定することはできます。

try:
    driver.find_element_by_id('test').click()
except:
  # 存在しない
ポイントはdriver.find_element_by_idの代わり、driver.find_elements_by_idを使います。一見同じように見えますが、前者の場合は要素が存在しない時に異常が発生します。後者なら、要素が存在しなくでも異常が発生しないです。
具体的に以下ように使います。

if len(driver.find_elements_by_id('test') > 0) :
    ele = driver.find_element_by_id('test')
 # 存在する時の処理
else:
  # 存在しない時の処理
driver.find_elements_by_idの他、driver.find_elements_by_namedriver.find_elements_by_xpathdriver.find_elements_by_class_namedriver.find_elements_by_css_selectordriver.find_elements_by_link_textdriver.find_elements_by_tag_nameなどなどが存在します。基本的にfind_element_by_xxとセットとなっています。

2019年8月20日火曜日

centosにopencv-pythonをインストールする方法

pythonとpipがインストールされている前提とします。
pythonで画像ファイルを圧縮機能を作るため、opencv-pythonを使うことに決めました。

早速、pip install opencv-pythonをうってっみたら、なんとエラーが発生しました。
 ERROR: Complete output from command /usr/bin/python3 -u -c 'import setuptools, tokenize;__file__='"'"'/tmp/pip-install-592jsl_n/numpy/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-2romtc2a/install-record.txt --single-version-externally-managed --compile:
    ERROR: Running from numpy source directory.
 
    Note: if you need reliable uninstall behavior, then install
    with pip instead of using `setup.py install`:
 
      - `pip install .`       (from a git repo or downloaded source
                               release)
      - `pip install numpy`   (last NumPy release on PyPi)
 
 
    blas_opt_info:
    blas_mkl_info:
    customize UnixCCompiler
      libraries mkl_rt not found in ['/usr/local/lib64', '/usr/local/lib', '/usr/lib64', '/usr/lib']
      NOT AVAILABLE
...略

python3.4-devが足りてないようです。 早速python3.4-devをインストールします。

yum list python34-devel*
yum install python34-devel
ようやく準備が整ったようで、再度pip install opencv-pythonをうったら、今度無事にインストールできました。

2019年8月16日金曜日

pythonとseleniumを使用して確実にページの先頭にスクロールする方法

調べればたくさん方法があると思いますが、何回試したがうまくいかなかったです。
最後辿り着くのが以下の通りでした。

driver = webdriver.Firefox()
driver.execute_script("window.scrollTo(0, 0);")

2019年7月8日月曜日

PythonでSeleniumのclickメソッドは効かない

PythonでSeleniumのclickメソッドがどうしても効かない問題に遭遇しました。

最初に使ったソースコードは以下の通りです。

from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://xxxxx/')  # 自分の検証サイトのURL
submit = driver.find_element_by_id("submitbutton")
submit.click()


調べたところ、要素はブラウザー上にクリックできない場所に存在している可能性があります。

でしたら、ブラウザーを最下部に移動してみようと考えました。

以下のコードを使って、最下部にスクロールしました。

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

再度検証したところだめでした。


再度調査したら、Seleniumが介在せずそのまま実行するならうまくいくかもしれませんの情報がありました。

Seleniumで直接javascriptを実行し、ボタンをクリックします。

driver.execute_script("document.getElementById('submitbutton').click();")

検証したところ、だめでした。

「ENTER」キーならうまくいった情報もありましたので、

「ENTER」キーを使ってクリックします。

submit.send_keys(Keys.ENTER)

結果としてだめでした。

気分を取り直して、要素に焦点を当たってからクリックするのも検証しました。

要素に焦点を当たります

ActionChains(driver).move_to_element(submit).perform()

それでもだめでした。

最後に辿り着いたのは「submit」メソッドでした。

driver.submit()

やっとうまくいきました。

フォームの中のボタン、クリックメソッドを使うより、サブミットの方がいいらいいです。

2018年2月26日月曜日

mac python3.6のインストール方法

1、まず、Pythonのオフィシャルサイトから最新のパッケージをダウンロードして、インストールします。
https://www.python.org/downloads/

2、インストール後、~/.bash_profileを修正し、適用させます
 vi ~/.bash_profile で以下の内容を追加
  alias python='python3'

3、~/.bash_profileを最近化にします。
 source ~/.bash_profile

最後、バージョンを確認
python --version
Python 3.6.4

2017年6月18日日曜日

python とあるインスタンスのクラス名を取得

Pythonの中、とあるインスタンスのクラス名を取得するには、以下の方法があります。
例:インスタンス「e」のクラス名を取得↓


 e.__class__.__name__

2017年6月16日金曜日

python 2つのListの要素が全て同じかを確かめる方法


 以下のfunctionで、2つのリストの要素が全ておなじかとうをチェックすることができます。
def checkEqual(L1, L2):
    return len(L1) == len(L2) and sorted(L1) == sorted(L2)

2017年5月29日月曜日

Pythonの中、配列あるいはdictを全部出力する方法

phpだと、「var_dump」、「print_r」でオブジェクトを全出力する方法があります。
Pythonなら、相当するメソッドがないのかなあ。。
Pythonの中、phpのvar_dumpを相当するメソッドは「pprint」です。使い方は以下の通りです。

from pprint import pprint

record = {'kinesis': {'data': 'test hoge ...'}} 

pprint record

2017年4月24日月曜日

python2系から3系にして、sha256ハッシュメソッドは「TypeError: key: expected bytes or bytearray, but got 'str'」

先日Python2.6からPython3.61にアップデートにしたら、元々問題なく動いてた「sha256」メソッドがこんなエラーになりました。↓
TypeError: key: expected bytes or bytearray, but got 'str'
解決方法は、引数はbytearrayにしてから渡す。
例:
 hmac.new(bytearray(self.access_key, "ASCII"), bytearray(base_code, "ASCII"), hashlib.sha256).hexdigest()

2017年4月23日日曜日

Pythonで配列をカンマでjoinをしようとしたら、「: ('sequence item 0: expected str instance, decimal.Decimal found',)」

 list = [3,5,12]

↑上記の配列をカンマで連結しようと思ったら、以下のエラーがでました。
<class 'tuple'>: ('sequence item 0: expected str instance, decimal.Decimal found',)

解決方法は、以下で示した通り、map関数を使う
myList = ','.join(map(str, list))