admin管理员组文章数量:1660700
from selenium import webdriver, common
import time
# 爬取今日头条的新闻
browser = webdriver.Chrome()
browser.maximize_window()
browser.get("https://www.toutiao/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("https://www.toutiao/ch/news_finance/")
index = 0
time.sleep(5)
# 滚轴顶头
browser.execute_script("window.scrollTo(0, 0)")
finally:
index += 1
版权声明:本文标题:爬取今日头条新闻selenium 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1729881422a1215967.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论