2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

検索から開くのめんどくさいねん。

Posted at

皆さんこんにちは。

今日は、Google検索していちいち新しいタブを使ってサイトを開くのがめんどくさいため、自動的にタブを開いてくれるソースコードを学びました。

使うモジュール

  • requests (インターネットからファイルやWebページをダウンロードする。)
  • sys (コマンドライン引数を取得するのに使う)
  • webbrowser(Python付属のモジュールで、指定したページをブラウザで開く。)
  • bs4 (HTMLを解析するのに使う。)

手順

  1. コマンドラインからの検索ワードをGoogleのURLと貼り付けて、検索画面をゲット。
  2. そこから検索結果のリンクを収集。
  3. 最後に一つ一つのURLを開く。

ソースコード

# ! python3
# lucky.py - Goole検索結果をいくつか開く

import requests
import sys
import webbrowser
import bs4

print('Googling...')
# 手順1
res = requests.get('http://www.google.com/search?q=' + ' '.join(sys.argv[1:]))
# 繋がっているか確認。(繋がっていなければ、エラーを出力.
res.raise_for_status()

# 手順2
# ゲットしたレスポンスからaタグのみを収集。
soup = bs4.BeautifulSoup(res.text, 'html.parser')
link_elems = soup.select('.kCrYT a')

# 最大を5つとしておく。
num_open = min(5, len(link_elems))

# 手順3
# 一つ一つのURLを開く。
for i in range(num_open):
    webbrowser.open('http://www.google.com/' + link_elems[i].get('href'))

上から読んでいくと、簡単ですね。

python lucky.py つよつよエンジニア 

とコマンドラインに打つとそれに関連するサイトが自動で開かれます。
さぁ、つよつよエンジニアになるために勉強しますか・・・。笑

少し分かってない部分。

最後に少し謎が残ってるところをメモ。
Chrome上の検証上では、classは"r"なので、select('.r a')をなるはずなのですが、それは変わってるんですよね😓
もしわかる方がいらっしゃれば是非ともご教授くださいませ。

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?