【Python3】Seleniumでidを指定してaタグのURLを取得する方法

2021年12月12日

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

SeleniumでaタグのURLを取得する方法を説明します。

youtube.comのトップ画面の動画URLを取得する場合で説明します。
aタグ周りのdomは以下のように構成されている前提となります。

<a id="video-title-link" class="yt-simple-endpoint style-scope ytd-rich-grid-media" aria-label="ラベル" title="タイトル" href="/watch?v=EqboAI-Vk-U">
	<yt-formatted-string id="video-title" class="style-scope ytd-rich-grid-media" aria-label="ラベル"></yt-formatted-string>
</a>

一つの要素のURLを取得する

from selenium.webdriver import Chrome
driver = Chrome()
driver.get("https://www.youtube.com/")
element = driver.find_element_by_id("video-title-link")
print(element.get_attribute("href"))

複数の要素のURLを取得する

from selenium.webdriver import Chrome
driver = Chrome()
driver.get("https://www.youtube.com/")
elements = driver.find_elements_by_id("video-title-link")
for element in elements:
    print(element.get_attribute("href"))

Selenium,Python

Posted by sena