Skip to content

Instantly share code, notes, and snippets.

@daiiz
Created February 23, 2015 06:02
Show Gist options
  • Save daiiz/320b9834a4c4cbae42c7 to your computer and use it in GitHub Desktop.
Save daiiz/320b9834a4c4cbae42c7 to your computer and use it in GitHub Desktop.
python学習日記 2日目
# -*- encoding: utf-8 -*-
import urllib
from bs4 import BeautifulSoup
def main():
# URL を指定するとそのファイルを開けるっぽい
my_page = 'http://daiz-projects.appspot.com/hoge/bar.html'
f = urllib.urlopen(my_page)
# f の型は一体何なのか調べてみる
print type(f) #=> <type 'instance'>
# とりあえず読んでみる
print f.read()
# h1タグの中身を取得してみたい
soup = BeautifulSoup(f)
# 綺麗に表示してみる
print soup.prettify()
# タイトルを表示できるか => タグも”込み”で取得される
print soup.title
# なんとかタグ無しで取得できないか => できる
print soup.title.text
# divタグは何個あるか
print len(soup.find_all('div'))
# 最初のdivタグを表示
print soup.find('div')
# 最後のdivタグを表示
print soup.find_all('div')[-1]
# idがaである要素を表示する
print soup.find(id='a')
# idがaである要素の子要素として、idがbであるものを表示する
id_a_tag = soup.find(id='a')
print id_a_tag.find(id='b')
# print soup.find(id='a').find(id='b') # 短縮してこう書くこともできる
#ドキュメント中の画像のURLをすべて表示する
for img_tag in soup.find_all('img'):
print img_tag['src']
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment