/Google_ad_lp.py Secret
Created
December 29, 2023 15:53
リスティング広告のLPを取得し、スクショ、
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from selenium import webdriver | |
from selenium.webdriver.common.by import By | |
from selenium.webdriver.common.keys import Keys | |
from selenium.webdriver.chrome.options import Options | |
import chromedriver_binary | |
from time import sleep | |
import pandas as pd | |
import datetime | |
import os | |
#スクレイピングの開始時間を設定 | |
now = datetime.datetime.now() | |
d_now = '{:%Y%m%d}_LP'.format(now) | |
if not os.path.isdir(d_now): | |
os.mkdir(d_now) | |
#selenumの設定 | |
options = Options() | |
options.add_argument('--headless') | |
# スクロールバーを非表示にする | |
options.add_argument('--hide-scrollbars') | |
driver = webdriver.Chrome(options=options) | |
d = [] | |
#Google検索にアクセス、 | |
driver.get('https://www.google.co.jp/') | |
ad_url_list =[] | |
#検索するキーワードの変数定義 | |
with open("research_list.txt",encoding='utf-8') as f: | |
research_keywords = [s.rstrip() for s in f.readlines()] | |
for research_keyword in research_keywords[:1]: | |
#キーワード検索開始 | |
elem = driver.find_element(by=By.NAME,value="q") | |
elem.clear() | |
elem.send_keys(research_keyword) | |
elem.submit() | |
assert "No results found." not in driver.page_source | |
sleep(2) | |
#リスティング広告に該当するlpを抽出 | |
try: | |
uEierd = driver.find_elements(by=By.CLASS_NAME, value="uEierd") | |
for i,ad in enumerate(uEierd): | |
ad_url = ad.find_element(by=By.CLASS_NAME, value="sVXRqc").get_attribute("href") | |
ad_text_list = ad.text.split("\n") | |
ad_title = ad_text_list[1] | |
ad_description ="\n".join(ad_text_list[4:]) | |
ad_url_list.append((ad_url,ad_text_list[2])) | |
print("="*30 ,i+1,"="*30) | |
print(ad_url) | |
print(ad_title) | |
print(ad_description) | |
#リスティングの内容(url・タイトル・ディスクリプションをいれる | |
d.append({ | |
"調査キーワード":research_keyword, | |
"タイトル":ad_title, | |
"ページURL":ad_url, | |
"説明文":ad_description}) | |
except: | |
pass | |
#取得したad_url_listにアクセスし、LPをスクショする | |
for i in set(ad_url_list): | |
driver.get(i[0]) | |
sleep(2) | |
w = driver.execute_script('return document.body.scrollWidth') | |
h = driver.execute_script('return document.body.scrollHeight') | |
driver.set_window_size(w, h) | |
sleep(2) | |
driver.save_screenshot(f'./{d_now}/{i[1]}.png') | |
driver.quit() | |
df = pd.DataFrame(d) | |
df.to_csv("search_ad.csv",index=False,encoding="utf-8-sig") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment