Python-data-science-python-reading-html-pages
提供:Dev Guides
Python-HTMLページの読み取り
beautifulsoupとして知られるライブラリ。 このライブラリを使用して、htmlタグの値を検索し、ページのタイトルやページ内のヘッダーのリストなどの特定のデータを取得できます。
Beautifulsoupをインストールする
Anacondaパッケージマネージャーを使用して、必要なパッケージとその依存パッケージをインストールします。
conda install Beaustifulsoap
HTMLファイルを読む
以下の例では、Python環境にロードされるURLへのリクエストを作成します。 次に、htmlパーサーパラメーターを使用して、htmlファイル全体を読み取ります。 次に、htmlページの最初の数行を印刷します。
import urllib2
from bs4 import BeautifulSoup
# Fetch the html file
response = urllib2.urlopen('http://finddevguides.com/python/python_overview')
html_doc = response.read()
# Parse the html file
soup = BeautifulSoup(html_doc, 'html.parser')
# Format the parsed html file
strhtm = soup.prettify()
# Print the first few characters
print (strhtm[:225])
上記のコードを実行すると、次の結果が生成されます。
<!DOCTYPE html>
<!--[if IE 8]><html class="ie ie8"> <![endif]-->
<!--[if IE 9]><html class="ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html>
<!--<![endif]-->
<head>
<!-- Basic -->
<meta charset="utf-8"/>
<title>
タグ値の抽出
次のコードを使用して、タグの最初のインスタンスからタグ値を抽出できます。
import urllib2
from bs4 import BeautifulSoup
response = urllib2.urlopen('http://finddevguides.com/python/python_overview')
html_doc = response.read()
soup = BeautifulSoup(html_doc, 'html.parser')
print (soup.title)
print(soup.title.string)
print(soup.a.string)
print(soup.b.string)
上記のコードを実行すると、次の結果が生成されます。
Python Overview
Python Overview
None
Python is Interpreted
すべてのタグの抽出
次のコードを使用して、タグのすべてのインスタンスからタグ値を抽出できます。
import urllib2
from bs4 import BeautifulSoup
response = urllib2.urlopen('http://finddevguides.com/python/python_overview')
html_doc = response.read()
soup = BeautifulSoup(html_doc, 'html.parser')
for x in soup.find_all('b'): print(x.string)
上記のコードを実行すると、次の結果が生成されます。
Python is Interpreted
Python is Interactive
Python is Object-Oriented
Python is a Beginner's Language
Easy-to-learn
Easy-to-read
Easy-to-maintain
A broad standard library
Interactive Mode
Portable
Extendable
Databases
GUI Programming
Scalable