0
0

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 1 year has passed since last update.

【python】SeleniumでChrome操作

Posted at

参考

import sys
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome import service as fs

if __name__ == "__main__":
    base_url = "https://www.google.com/"

    url = f"{base_url}/"

    options = Options()

    # Browser
    CHROMEDRIVER = './chromedriver'
 
    # ドライバー指定でChromeブラウザを開く
    chrome_service = fs.Service(executable_path=CHROMEDRIVER)
    driver = webdriver.Chrome(service=chrome_service)
    driver.get(url)

    name = "q"  # elementのname
    search_word = "python selenium"  # 検索するワード

    try:
        marker = driver.find_element(By.NAME, name)
        marker.send_keys(search_word)
        marker.send_keys(Keys.ENTER)

        xpath = "//div[@id='search']//a/h3"  # 検索結果のtitleのxpath
        title_elements = driver.find_elements(By.XPATH, xpath)  # 結果の取得

    except Exception as err:
        print(err)
        sys.exit(1)

    for title_element in title_elements:
        if len(title_element.text) > 0:
            # 検索結果のtitleの親のxpathを取得
            href_element = title_element.find_element(By.XPATH, "..")
            # 出力
            print(
                f'titele={title_element.text.replace(" ...", "")} url={href_element.get_attribute("href")}'
            )


    time.sleep(5)
    driver.close()

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?