Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TUT Python スクレイピングハンズオン

Avatar for panakuma panakuma
February 03, 2018

TUT Python スクレイピングハンズオン

Avatar for panakuma

panakuma

February 03, 2018
Tweet

More Decks by panakuma

Other Decks in Education

Transcript

  1. スクレイピング (2) • 行っていることの解説 • まず最初の2行 from urllib import request

    from bs4 import BeautifulSoup as BS • urllibというライブラリからrequestという機能をインポート • bs4というライブラリからBeautifulSoupという機能をインポートしてBSという別 名を付与
  2. スクレイピング (3) url = "http://imotosae.com/news/" req = request.Request(url) res =

    request.urlopen(req) html = res.read() • 変数urlにスクレイピングするサイトのurlを代入 • urlを取得するというオブジェクトをreqに代入 • reqを実行して得られたオブジェクトをresに代入 • htmlにresをStringとして代入
  3. スクレイピング (4) soup = BS(html, "lxml") topics = soup.find_all('h1', 'c-thumb-index__title')

    for i in range(len(topics)): print(topics[i].string, "\n") • htmlを「lxml」というHTMLパーサを使って内容を解析して 結果を変数 soup に代入 • soupの中から「c-thumb-index__title」というクラス名を持つ「h1」タ グを抽出して変数 topics にリストとして代入 • topicsの中身を出力