ようやくやりたいとこまで来たな…というところです。
Python Webスクレイピング 実践入門を参考に、でもPython3に対応させつつ実践してみます。
まずはSSHにログインしたあと、pythonコマンドをうちます。
python3
Python3 系でウェブスクレイピングを行う
Python3 系でウェブスクレイピングを行うときは
import urllib.request, urllib.error
とインポートする。import urllib2は Python2 系で Python3では使用できないぽい。
参考:Python3系でurllib2は使えない:代わりにurllib.requestとurllib.errorを使う
タイトルタグとタイトルを取得する
import urllib.request, urllib.error from bs4 import BeautifulSoup url = 'https://www.mathpython.com/' html = urllib.request.urlopen(url=url) soup = BeautifulSoup(html, "html.parser") # タイトル要素を取得する → <title>日本経済新聞</title> title_tag = soup.title # 要素の文字列を取得する → 日本経済新聞 title = title_tag.string # タイトル要素を出力 print(title_tag) # タイトルを文字列を出力 print(title)
これでタイトルタグとタイトルがそれぞれ返ってきました。
# タイトル要素を出力 print(title_tag) <title>日本経済新聞</title> # タイトルを文字列を出力 print(title) 日本経済新聞
タイトルの文字列print(title)はprint(soup.title.string)でも取得できました。