window_handles[] 自己接觸的常用場合
1鸠澈、頁面切換
2、在使用.click()切換頁面后截驮,獲取最新的page_source
【下面放一個demo笑陈,spider第一個公眾號的最新前10篇文章】
from seleniumimport webdriver
from selenium.webdriver.support.waitimport? WebDriverWait
# 配置相應(yīng)參數(shù)
options= webdriver.ChromeOptions()
options.add_argument('headless')
driver= webdriver.Chrome(
executable_path='/usr/local/bin/chromedriver',
chrome_options=options
)
# 搜索 key 打開搜索公眾號頁面
begin_url= 'https://weixin.sogou.com'
timeout= 5
search_key= 'python'
driver.get(begin_url)
print(driver.title)
search_input= WebDriverWait(driver,timeout).until(
lambda d: d.find_element_by_xpath('//input[@id="query"]')
)
search_input.send_keys(search_key)
search_account_btn= WebDriverWait(driver,timeout).until(
lambda d: d.find_element_by_xpath('//input[@uigs="search_account"]')
)
search_account_btn.click()
# 索取公眾號鏈接
search_account= WebDriverWait(driver,timeout).until(
lambda? d:d.find_elements_by_xpath('//a[starts-with(@uigs,"account_name_")]')
)
import time
time.sleep(3)
# for account in search_account:
#? ? print(account.get_attribute('href'))
# 打開首個公眾號頁面
for accountin search_account:
? ? account.click()
break
time.sleep(timeout)
#?在使用.click()切換頁面后,獲取最新的page_source,否則難以獲取最新頁面的源碼
driver.switch_to.window(driver.window_handles[-1])
# 索取首公眾號的10(不一定是10篇)篇文章
search_titles= WebDriverWait(driver,timeout).until(
lambda? d: d.find_elements_by_xpath('//h4[@class="weui_media_title"]')
)
for titlein search_titles:
? ? print(title.text,'-----',title.get_attribute('hrefs'))
# 關(guān)閉driver
driver.close()