Pythonのseleniumでhref属性を取得する方法

2023年10月9日

PythonのSeleniumを使用して<a>タグのhref属性を取得するには、get_attributeメソッドを使用します。以下は、Seleniumを使用して<a>タグのhref属性を取得する方法の例です。

python
from selenium import webdriver

# WebDriverのインスタンスを作成(例:Chrome用のWebDriver)
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')

# ウェブページを開く
driver.get('https://example.com')

# <a>タグを取得
a_elements = driver.find_elements_by_tag_name('a')

# 各<a>タグのhref属性を取得して表示
for a_element in a_elements:
    href_attribute = a_element.get_attribute('href')
    print("リンクのURL(href属性):", href_attribute)

# WebDriverを終了
driver.quit()

このコードでは、Seleniumを使用してWebDriverのインスタンスを作成し、指定したURLのウェブページを開きます。それからfind_elements_by_tag_nameメソッドを使用して、すべての<a>タグ(リンク要素)を取得します。各<a>タグに対してget_attributeメソッドを使用してhref属性の値を取得し、それを表示します。

この方法を使用して、Seleniumを使ってウェブページからリンクのURLを取得できます。必要な処理を行う際にこれらのURLを活用できます。