buto > /dev/null

だいたい急に挑戦してゴールにたどり着かずに飽きる日々です

【朝活】【python】スクレイピング

Pythonを始めると「クローリング」「スクレイピング」をよく見かけます

クローリング

WEBページのHTMLやPHPを取得すること SEO対策ではGoogleクローラーにWEBページを見つけやすくする工夫をする 検索エンジンクローラーがWEBページを巡回することを指している

スクレイピング

WEBページからデータを取得して加工する データ加工があるとスクレイピングなのかな

Requestsライブラリでデータ取得

import requests

url = "https://nekomoni.com/detail/index.html#transmitter"

response = requests.get(url)
response.encoding = response.apparent_encoding

print(response.text)

これだけでねこもにの製品ページHTMLが取得されます

BeautifulSoupで「ねこ」を見つける

from bs4 import BeautifulSoup

# requests.get(url)で取得したHTML
bs = BeautifulSoup(response.text, 'html.parser')
# <img>タグを探す
bs_img = bs.find_all('img')

count = 0
file_content = ''

for img in bs_img:
    title = img['alt']
    img_url = img['src']
    search_word = 'ねこ'
    
    # <img>alt属性に「ねこ」が含まれている
    if search_word in title:
        count += 1
        if count != 1:
            file_content += '\n'
    
    line = title + ',' + img_url
    file_content += line

# 「タイトル,画像URL」をcsvファイルに出力        
with open('nekomoni.csv', 'w', encoding='utf-8') as f:
    f.write(file_content)

# 同じ記号を連続で表示したいときは掛け算
print('#'*50)
print('検索ワード:{}, ヒット数:{}'.format(search_word, count))

################################################## 検索ワード:ねこ, ヒット数:6

f:id:butorisa:20201020133405p:plain

スクレイピングを使いこなすと分析に使うデータも効率よく作成できそうです!!