【Python3】Seleniumでページ内全てのaタグのURLを取得する方法

2021年12月9日

おはこんばんにちはせなです。

Seleniumを使用してページ内のaタグのURLを取得する方法を説明します。

google.comの画面から取得する場合を例にして説明します。

from selenium.webdriver import Chrome
driver = Chrome()
driver.get("https://www.google.com/")
# aタグのhrefをelementでリスト化
elements = driver.find_elements_by_xpath("//a[@href]")
for element in elements:
    print(element.get_attribute("href"))

上記実行後の結果が以下となります。

https://about.google/?fg=1&utm_source=google-JP&utm_medium=referral&utm_campaign=hp-header
https://store.google.com/JP?utm_source=hp_header&utm_medium=google_ooo&utm_campaign=GS100042&hl=ja-JP
https://mail.google.com/mail/&ogbl
https://www.google.co.jp/imghp?hl=ja&ogbl
https://www.google.co.jp/intl/ja/about/products
https://accounts.google.com/ServiceLogin?hl=ja&passive=true&continue=https://www.google.com/&ec=GAZAmgQ
https://www.google.com/#
https://www.google.com/intl/ja_jp/ads/?subid=ww-ww-et-g-awa-a-g_hpafoot1_1!o2&utm_source=google.com&utm_medium=referral&utm_campaign=google_hpafooter&fg=1
https://www.google.com/services/?subid=ww-ww-et-g-awa-a-g_hpbfoot1_1!o2&utm_source=google.com&utm_medium=referral&utm_campaign=google_hpbfooter&fg=1
https://google.com/search/howsearchworks/?fg=1
https://policies.google.com/privacy?hl=ja&fg=1
https://policies.google.com/terms?hl=ja&fg=1
https://www.google.com/preferences?hl=ja&fg=1
https://www.google.com/advanced_search?hl=ja&fg=1
https://www.google.com/history/privacyadvisor/search/unauth?utm_source=googlemenu&fg=1
https://www.google.com/history/optout?hl=ja&fg=1
https://support.google.com/websearch/?p=ws_results_help&hl=ja&fg=1

簡単に取得できますね。

Selenium,Python

Posted by sena