標籤彙整: selenium

Google關鍵字搜尋,將搜尋結果排名紀錄下來

使用Python撰寫自動化搜尋特定關鍵字

Google關鍵字搜尋將搜尋結果排名紀錄下來

Selenium 使用 Chrome 瀏覽器 webdriver

SEO (Search Engine Optimization),是維護網站非常重要的一項工作,利用這個小程式可以自動化的搜尋關鍵字,並將搜尋排名結果存入檔案,以利分析成效與後續的持續優化。

需要先安裝 selenium 套件

下載 Chrome 瀏覽器 webdriver

額外會需要用到兩隻檔案,需要先建立好放置於py檔同層資料夾下

site.csv : 裡面放要搜尋的網站位置

terms.csv : 搜尋關鍵字

from selenium import webdriver
import csv
import time

chromedriver = "/Users/chifu/Documents/chromedriver"
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
driver = webdriver.Chrome(chromedriver, chrome_options=chrome_options)
csvr_site = csv.reader(open('site.csv', 'r'))
csvr_terms = csv.reader(open('terms.csv', 'r'))
outfile = open('rank.csv', 'w')
csvwriter = csv.writer(outfile)
search_pages = 5

for s in csvr_site:
	site = s[0]

for row in csvr_terms:
	print(row[0])
	current_page = 1
	while current_page <= search_pages:
		if current_page == 1:
			driver.get("https://www.google.com.tw/search?q=%s" % row[0])
		else:
			driver.get(next_pageurl)
		time.sleep(1)
		doms = driver.find_elements_by_css_selector("div.rc h3.r a")
		next_pageurl = driver.find_element_by_css_selector("a#pnnext.pn").get_attribute("href")
		counter = 0
		rank = "not found"
		for dom in doms:
			counter += 1	
			href = dom.get_attribute("href")
			if site in href:
				rank = counter
				break
		if rank != "not found":
			break
		current_page += 1

	csvwriter.writerow([row[0], current_page, rank])
	outfile.flush()
	time.sleep(1)
driver.close()

相關API參考