In [1]:
import requests
import bs4
In [2]:
# Requestsでgihyo.jpのページのデータを取得
import requests
r = requests.get('http://gihyo.jp/lifestyle/clip/01/everyday-cat')
r.status_code # ステータスコードを取得
Out[2]:
In [3]:
r.text[:50] # 先頭50文字を取得
Out[3]:
In [4]:
# JSON形式のAPIレスポンスを取得
r = requests.get('https://connpass.com/api/v1/event/?keyword=python')
data = r.json() # JSONをデコードしたデータを取得
for event in data['events']:
print(event['title'])
In [5]:
# 各種HTTPメソッドに対応
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post('http://httpbin.org/post', data=payload)
r = requests.put('http://httpbin.org/put', data=payload)
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')
In [6]:
# Requestsの便利な使い方
r = requests.get('http://httpbin.org/get', params=payload)
r.url
Out[6]:
In [7]:
r = requests.get('https://httpbin.org/basic-auth/user/passwd', auth=('user', 'passwd'))
r.status_code
Out[7]:
In [8]:
# Beautiful Soup 4で「技評ねこ部通信」を取得
import requests
from bs4 import BeautifulSoup
r = requests.get('http://gihyo.jp/lifestyle/clip/01/everyday-cat')
soup = BeautifulSoup(r.content, 'html.parser')
title = soup.title # titleタグの情報を取得
type(title) # オブジェクトの型は Tag 型
Out[8]:
In [9]:
print(title) # タイトルの中身を確認
print(title.text) # タイトルの中のテキストを取得
In [10]:
# 技評ねこ部通信の1件分のデータを取得
div = soup.find('div', class_='readingContent01')
li = div.find('li') # divタグの中の最初のliタグを取得
print(li.a['href']) # liタグの中のaタグのhref属性の値を取得
print(li.a.text) # aタグの中の文字列を取得
li.a.text.split(maxsplit=1) # 文字列のsplit()で日付とタイトルに分割
Out[10]:
In [11]:
# 技評ねこ部通信の全データを取得
div = soup.find('div', class_='readingContent01')
for li in div.find_all('li'): # divタグの中の全liタグを取得
url = li.a['href']
date, text = li.a.text.split(maxsplit=1)
print('{},{},{}'.format(date, text, url))
In [12]:
# タグの情報を取得する
div = soup.find('div', class_='readingContent01')
type(div) # データの型はTag型
Out[12]:
In [13]:
div.name
Out[13]:
In [14]:
div['class']
Out[14]:
In [15]:
div.attrs # 全属性を取得
Out[15]:
In [16]:
# さまざまな検索方法
a_tags = soup.find_all('a') # タグ名を指定
len(a_tags)
Out[16]:
In [17]:
import re
for tag in soup.find_all(re.compile('^b')): # 正規表現で指定
print(tag.name)
In [18]:
for tag in soup.find_all(['html', 'title']): # リストで指定
print(tag.name)
In [19]:
# キーワード引数での属性指定
tag = soup.find(id='categoryNavigation') # id属性を指定して検索
tag.name, tag.attrs
Out[19]:
In [20]:
tags = soup.find_all(id=True) # id属性があるタグを全て検索
len(tags)
Out[20]:
In [21]:
div = soup.find('div', class_='readingContent01') # class属性はclass_と指定する
div.attrs
Out[21]:
In [22]:
div = soup.find('div', {'class': 'readingContent01'}) # 辞書形式でも指定できる
div.attrs
Out[22]:
In [23]:
# CSSセレクターを使用した検索
soup.select('title') # タグ名を指定
Out[23]:
In [24]:
tags = soup.select('body a') # body タグの下のaタグ
len(a_tags)
Out[24]:
In [25]:
a_tags = soup.select('p > a') # pタグの直下のaタグ
len(a_tags)
Out[25]:
In [26]:
soup.select('body > a') # bodyタグの直下のaタグは存在しない
Out[26]:
In [27]:
div = soup.select('.readingContent01') # classを指定
div = soup.select('div.readingContent01')
div = soup.select('#categoryNavigation') # idを指定
div = soup.select('div#categoryNavigation')
a_tag = soup.select_one('div > a') # 最初のdivタグ直下のaタグを返す