最近有个需求需要爬取 GSC 的页面,先用 requests 获取页面,配合 beautifulsoup 进行解析即可,还需要搞定登录状态的问题。
用 requests 怎么都搞不定登录,Google 的技术还是非常前沿的,登录页面的js做了非常多的加密或者压缩,很难破解。最后用 Selenium 搞定了这个事情。默认的包莫名其妙会触发 Google 的反爬机制,始终提示浏览器不安全,好在找到一个专门做了针对的扩展—— undetected-chromedriver,解决了这个问题。
直接贴代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
import undetected_chromedriver.v2 as uc
chrome_options = uc.ChromeOptions()
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-popup-blocking")
chrome_options.add_argument("--profile-directory=Default")
chrome_options.add_argument("--ignore-certificate-errors")
chrome_options.add_argument("--disable-plugins-discovery")
chrome_options.add_argument("--incognito")
chrome_options.add_argument('--no-first-run')
chrome_options.add_argument('--no-service-autorun')
chrome_options.add_argument('--no-default-browser-check')
chrome_options.add_argument('--password-store=basic')
chrome_options.add_argument('--no-sandbox')
driver = uc.Chrome(options=chrome_options, executable_path='./driver/chromedriver')
driver.delete_all_cookies()
driver.get("https://accounts.google.com/signin/v2/identifier?service=accountsettings&continue=https%3A%2F%2Fmyaccount.google.com%3Futm_source%3Daccount-marketing-page%26utm_medium%3Dgo-to-account-button&flowName=GlifWebSignIn&flowEntry=ServiceLogin")
driver.find_element_by_xpath('//input[@type="email"]').send_keys(email)
input = WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.XPATH, '//*[@id="identifierNext"]')))
input.click()
WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.XPATH, '//*[@id="password"]/div[1]/div/div[1]/input')))
driver.find_element_by_xpath('//*[@id="password"]/div[1]/div/div[1]/input').send_keys(password)
input = WebDriverWait(driver, 100).until(expected_conditions.element_to_be_clickable((By.XPATH, '//*[@id="passwordNext"]/div/button')))
input.click()
time.sleep(5)
cookies = driver.get_cookies()
cookies_arr = []
for c in cookies:
if c['domain'].endswith('.google.com'):
cookies_arr.append(f'{c["name"]}={c["value"]}')
driver.close()
print( "; ".join(cookies_arr))



嗨,您好,我想請問你在碰到反爬機制時,是如何找到undetected-chromedriver這個package的。因為我最近參考別人的code,我爬了很久都進不去,後來發現有人也是用這個package才爬到的。因為我是新手,我翻了台灣幾本書都沒有寫道這個package,而且這個package在台灣的網路上也沒有太多資訊。因此想請教您,在碰到爬不進的網站中,要如何找到更好的辦法。譬如您是如何找到undetected-chromedriver這個package,希望您能有空分享一下。謝謝
hi,最近比较忙,刚看到评论。我当时是在爬 GSC(Google Search Console)这个特定的网站,默认的 Selenium 始终提示「浏览器不安全」,我通过这个关键词的 Google 搜索结果发现的这个包,不过当时的文章已经忘记是哪一篇了。所以如果我有什么值得分享的话就是把问题定位出来,通过搜索引擎去查一下,因为很多时候不会是第一个碰到问题的人。另外如果你爬的很多是中文的站点,可以关注一些 github 聚合的仓库,也可以学习很多,比如 https://github.com/Jack-Cherish/python-spider