window_handles[] 自己接触的常用场合
1、页面切换
2、在使用.click()切换页面后,获取最新的page_source
【下面放一个demo,spider第一个公众号的最新前10篇文章】
from seleniumimport webdriver
from selenium.webdriver.support.waitimport WebDriverWait
# 配置相应参数
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'))
# 关闭driver
driver.close()