新卒から文系エンジニア→人材業界に転職した人のブログ

新卒から文系エンジニア→人材業界に転職。技術・スキルがないためブログを通して勉強。その後、IT業界の業界知識が活かせる人材業界へ。異業種×異職種の転職経験有り。

このエントリーをはてなブックマークに追加

【python】スクレイピングの第一歩 特定のサイトから情報(URL/タイトル)を抽出する

■やりたいこと


はてなブログのタイトルとURLを使って出力する」


WEB上の実行環境を利用して、pythonで作ってみました。
※環境準備は5分以内に終わる簡単なものです。

Pythonによるスクレイピング超絶入門|Dai|noteの記事経由から知りました、ありがとうございます。


改めて、自分で書いてみて動くと楽しいですねーー

有用なものに応用できないか引き続きやってみます。

■参考コード

# Beautiful Soupのインポート
from bs4 import BeautifulSoup
import requests

#対象のWEBサイトにリクエストを送り、コードを取得
response = requests.get("http://forse.hatenablog.com/")
# BeautifulSoupの初期化
html_doc = response.text
 # htmlをパース
soup = BeautifulSoup(html_doc, 'html.parser')

#print(soup.prettify()) # 左記の処理でHTMLをインデントし、表示も可能

#サイト上にある対象リンクだけを取り出したいため
blog_str = 'http://forse.hatenablog.com/entry'

#リンクをリストに格納
list1 = soup.find_all('a')

#for文でリストを取り出していき、中味が空でないかつ対象リストのみを表示
for item in list1:
  url = item.get('href')
  if  item.string and url:
    if not  url.find(blog_str) == -1 :
      print(item.string)
      print(item.get('href'))


※実行環境の準備は、以下を参考しました。

note.mu

.hatena-module:nth-of-type(10) { background: transparent; } .hatena-module:nth-of-type(10) .hatena-module-title{ display: none; } .hatena-module:nth-of-type(10) .hatena-module-body { padding: 0; }