LoginSignup
1
0

More than 3 years have passed since last update.

Pythonを試す

Last updated at Posted at 2020-08-08

はじめに

気になっていたPythonを試します。環境はWindows10です。

準備

Anaconda3

Pythonのディストリビューション。
Python単体でDLしてもいいですが、ちょっと調べてみると
よく使うライブラリ等をすでに含んでいるAnaconda3の方がよさそうでしたのでこっちをいれてみます。
以下の64-Bit Graphical Installer (466 MB)をダウンロードしてすべてデフォルトでインストールしました。
https://www.anaconda.com/products/individual

インストール後、環境変数にバイナリファイルの場所を追加します。
C:\Users\xxxxxx\anaconda3

VS code

VSCodeで検索してダウンロード。
インストール後、左メニューの拡張機能から以下を追加。

  • 「Python Extension Pack」
  • 「Japanese Language Pack for Visual Studio code」(日本語化したい場合)

コマンドプロンプトから以下のコマンドを打ってバージョン表示できれば環境設定完了。

C:\Users\xxxxxx> python -V
Python 3.8.3

実装

testディレクトリを作成してその中に「test.py」的なファイルを作ってみます。

test.py
print("test!!")

実行

View(表示)から「ターミナル」を選択し、ターミナルを表示させます。
開いているpyファイルのディレクトリでPowerShellが起動するので以下のコマンドを実施。
すると、「test!!」が表示されます。

powershell
PS C:\Users\xxxxx\workspace\test> python test.py
test!!

スクレイピングを試してみます。
BeautifulSoupを使用すると便利なようです。
スクレイピングする前に許可されているかを必ずrobots.txtと利用規約で確認してください!!

test.py
import requests
import pandas as pd
from bs4 import BeautifulSoup
#スクレイピングするURL
url = 'xxxxxxxx'
response = requests.get(url)
response.encoding = response.apparent_encoding
#BeautifulSoup オブジェクトに変換
bs = BeautifulSoup(response.text, 'html.parser')
#class属性にclass123が指定されているh2タグを取得
tags = bs.find_all('h2', attrs={'class': 'class123'})

for tag in tags:
    print(tag,end='\n')

もし「numpyが見つからない」みたいなエラーが出る場合はパスが不足しているので
環境変数に以下のライブラリディレクトリを追加してVScodeを再起動します。
C:\Users\xxxxx\anaconda3\Library\bin

あとがき

スクレイピングはJavascriptよりもとても簡単にできました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0