爬取今日头条新闻selenium

from selenium import webdriver, common
import time
# 爬取今日头条的新闻
browser = webdriver.Chrome()
browser.maximize_window()
browser.get("https://www.toutiao.com/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.com/ch/news_finance/")
        index = 0
        time.sleep(5)
        # 滚轴顶头
        browser.execute_script("window.scrollTo(0, 0)")
    finally:
        index += 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值