#author("2022-11-02T04:48:09+00:00","","") #author("2022-11-02T04:50:35+00:00","","") [[中市]] **【BeautifulSoup4でのスクレイピング】[#i495c384] コマンドプロンプトからBeautifulSoup4をインストールする。 pip install beautifulsoup4 requestsもインストール pip install requests 以下をpythonファイルに入力 import requests from bs4 import BeautifulSoup import csv import re ↓でGoogle検索するキーワードを設定 search_word = 'python' 上位から何件までのサイトを抽出するか指定する 今回は10件 pages_num = 10 + 1 print(f'【検索ワード】{search_word}') Googleから検索結果ページを取得する url = f'https://www.google.co.jp/search?hl=ja&num={pages_num}&q={search_word}' request = requests.get(url) Googleのページ解析を行う soup = BeautifulSoup(request.text, "html.parser") search_site_list = soup.select('div.kCrYT > a') ページ解析と結果の出力 for rank, site in zip(range(1, pages_num), search_site_list): try: site_title = site.select('h3.zBAuLc')[0].text except IndexError: site_title = site.select('img')[0]['alt'] site_url = site['href'].replace('/url?q=', '') 結果を出力する print(str(rank) + "位: " + site_title + ": " + site_url) csv出力はまだ 結果 #ref(baba.png,,結果) **【seleniumでのスクレイピング】[#i495c384] コマンドプロンプトからseleniumをインストールする。 pip install selenium==3.141.0 下のリンクに行ってクロームドライバーをインストール、解凍。 [[Chrome Driver:https://sites.google.com/a/chromium.org/chromedriver/downloads]] pythonファイルに入力していく。 from selenium import webdriver from selenium.webdriver.chrome.options import Options from time import sleep import csv import datetime options = Options() driver = webdriver.Chrome('C:/Users/nasut/Desktop/chromedriver',options=options) driver.get('https://www.google.co.jp') クロームドライバーが置いてあった場所は C:\Users\nasut\Desktopだったが、 [\]を使用することでエラーが出たため「/」を使用した。 search_bar = driver.find_element_by_name("q") search_bar.send_keys("python") search_bar.submit() ↑で検索ワードを変更 csv_date = datetime.datetime.today().strftime("%Y%m%d") csv_file_name = "google_python_" + csv_date + ".csv" f = open(csv_file_name, "w", encoding="CP932", errors="ignore") writer = csv.writer(f, lineterminator="\n") csv_header = ["検索順位","タイトル","URL"] writer.writerow(csv_header) i = 0 item = 1 while True: i = i + 1 sleep(1) for elem_h3 in driver.find_elements_by_xpath("//a/h3"): elem_a = elem_h3.find_element_by_xpath("..") print(elem_h3.text) print(elem_a.get_attribute("href")) csvlist = [] csvlist.append(str(item)) csvlist.append(elem_h3.text) csvlist.append(elem_a.get_attribute("href")) writer.writerow(csvlist) item = item + 1 next_link = driver.find_element_by_id("pnnext") driver.get(next_link.get_attribute("href")) if i > 0: break f.close() 今回はあまり理解できなかったので妥協して、繰り返しを1回で止めることで 1ページを取り込むこととする 結果 グーグルクロームの画面が開き、pythonと検索する。 1ページ目を取り込み、2ページ目に遷移して終了する。 #ref(google_python_20221102.csv,,結果) **【参考資料】[#i495c384] [[図解!PythonでSeleniumを使ったスクレイピングを徹底解説!(インストール・使い方・Chrome):https://ai-inter1.com/python-selenium/]] [[【Webスクレイピング入門】Google検索の上位サイトを件数指定して表示する方法:https://rurukblog.com/post/WebScraping-Google-Top/]]