from selenium import webdriver, common
import time
# 爬取今日头条的新闻
browser = webdriver.Chrome()
browser.maximize_window()
browser.get("/ch/news_finance/")
time.sleep(3)
# 获取13条网页文章
index = 1
while index < 13:
try:
# 得到网页上显示的新闻的连接
web = browser.find_element_by_xpath("/html/body/div/div[4]/div[2]/div[2]/div/div/div/ul/li["+str(index)+"]/div/div[1]/div/div[1]/a")
print(web.get_attribute("href"))
# 模拟点击
web.click()
# 由于打开了新的连接该步骤是让selenium跳转到新的页面操作
pagenum = browser.window_handles
browser.switch_to.window(pagenum[1])
time.sleep(5)
# 操作js命令 注意return
title = None
try:
# 如果使用find element by xxx 会出现异常,所以折中选择js操作
title = browser.execute_script("return document.getElementsByClassName('article-title')[0].innerText")
except common.exceptions.WebDriverException as e:
print("标题有异常", e)
print(title)
browser.close()
browser.switch_to.window(pagenum[0])
time.sleep(3)
# 当流量的标题大于4个后,拖动滚动条
browser.execute_script("window.scrollTo(0," + str(index * 100) + ")")
time.sleep(2)
except common.exceptions.WebDriverException as e:
# 当有跳转的时候直接刷新页面 从头开始爬取
print("有跳转", e)
browser.get("/ch/news_finance/")
index = 0
time.sleep(5)
# 滚轴顶头
browser.execute_script("window.scrollTo(0, 0)")
finally:
index += 1