[python]トラブルシューティング
printの書き方がver3で変わってる。
print "Hello world" # python 2.x
print("Hello world") # python 3.x
ModuleNotFoundError: No module named 'urllib2'
インストールされてなければ以下でインストール。
pip install urllib2
また、書き方がver3で変わってる事に注意。
import urllib2 # python 2.x
import urllib.request, urllib.error # python 3.x
AttributeError: module 'urllib' has no attribute 'urlopen'
python3で書き方が変わってる。
html = urllib2.urlopen(url) # python 2.x urllib2
html = urllib.request.urlopen(url) # python 3.x urllib
AttributeError: 'NoneType' object has no attribute 'text'
print soup.select_one("#CONTENTS_MARROW > xxx > yyy > span.prices").text
取得したオブジェクトにtextアトリビュートがないって事かな。
print soup.select_one("#CONTENTS_MARROW > xxx > yyy > span.prices")
CSSセレクタの指定方法例
(注) print構文がprint()なのは、python3.x系です。
使ったソースはこれ。
# -*- coding: utf-8 -*-
import urllib.request
from bs4 import BeautifulSoup
# urlのHTMLを取得
url = 'https://algorithm.joho.info/'
html = urllib.request.urlopen(url)
# htmlをBeautifulSoupでパース
soup = BeautifulSoup(html, "html.parser")
# CSSセレクタで指定したタグ内のコンテンツを表示
print(soup.select_one("#post-17926 > div > footer > p > span.category > a").get('href'))
https://algorithm.joho.info/
print(soup.select_one("#post-17926 > div > footer > p > span.category > a").text)
電気・電子工学
--> 成功
print(soup.select_one("#post-17926 > div > footer > p > span.category > a").get('href'))
https://algorithm.joho.info/category/denki-denshi/
--> 成功
Anaconda3 import numpyに失敗する
Anaconda3-2019.03-Windows-x86_64.exe
でWindows 10 Homeにインストール。
ユーザの環境変数PATHの先頭に以下を追加。
C:\Users\marud\Anaconda3
C:\Users\marud\Anaconda3\Library\mingw-w64\usr\bin
C:\Users\marud\Anaconda3\Library\usr\bin
C:\Users\marud\Anaconda3\scripts
コマンドプロンプト起動。
C:\Users\marud>python
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Warning:
This Python interpreter is in a conda environment, but the environment has
not been activated. Libraries may fail to load. To activate this environment
please see https://conda.io/activation
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>> import numpy
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\marud\Anaconda3\lib\site-packages\numpy\__init__.py", line 140, in
from . import _distributor_init
File "C:\Users\marud\Anaconda3\lib\site-packages\numpy\_distributor_init.py", line 34, in
from . import _mklinit
ImportError: DLL load failed: 指定されたモジュールが見つかりません。
>>>
エラーになる。
ぐぐると、この問題けっこう起こってるみたい。
原因がわからないので、UbuntuにAnacondaインストールしてみよう。