Created
February 23, 2015 06:02
-
-
Save daiiz/320b9834a4c4cbae42c7 to your computer and use it in GitHub Desktop.
python学習日記 2日目
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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