プログラミングを学んだなら、AtCoder Beginners Selectionが難なく解ける程度の実装力は身につけておきたいですね。

ウェブスクレイピング

以下のサイトを用いる。
HTML,CSS

スクレイピング全般

BeautifulSoup

XPathについて

Selenium

実際のコード


# https://myafu-python.com/webmarketing/google-result/
# https://yuki.world/python-selenium-quickest-setup/
# https://programmer-life.work/python/selenium-find_element_by_class_name-deprecated

# スクレイピングに必要なライブラリをインポート
import openpyxl
from time import sleep
import chromedriver_binary
from selenium import webdriver
from selenium.webdriver.common.by import By

# from bs4 import BeautifulSoup
# import requests
# import csv

# オプション定義
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-logging"])
options.use_chromium = True

# googleで検索する文字
search_string = "防災井戸 inurl:https://www.pref.osaka.lg.jp/"

# Seleniumを使うための設定とgoogleの画面の表示
INTERVAL = 2.5
URL = "https://www.google.com/"
driver = webdriver.Chrome(options=options)
sleep(INTERVAL)
driver.get(URL)
sleep(INTERVAL)

# 文字を入力して検索
driver.find_element(By.NAME, "q").send_keys(search_string)
driver.find_elements(By.NAME, "btnK")[1].click()
sleep(INTERVAL)

# 検索結果の一覧を取得する
results = []
while True:
    g_ary = driver.find_elements(By.CLASS_NAME, "g")
    for g in g_ary:
        result = {}
        result["url"] = g.find_element(By.CSS_SELECTOR, ".yuRUbf a").get_attribute("href")
        result["title"] = g.find_element(By.TAG_NAME, "h3").text
        results.append(result)

    if len(g_ary) == 10:
        driver.find_element(By.ID, "pnnext").click()
        sleep(INTERVAL)
    else:
        break

# エクセルファイルに書き込み
excel = r"c:\記事収集\google.xlsx"
wb = openpyxl.load_workbook(excel)

sheet = wb["input"]
sheet["a1"] = "タイトル"
sheet["b1"] = "URL"

for row, result in enumerate(results, 2):
    sheet[f"a{row}"] = result["title"]
    sheet[f"b{row}"] = result["url"]

wb.save(excel)
driver.close()

print("finish")