创新实训【4】——爬虫新浪新闻

爬取内容

我爬取了新浪新闻中有关山东大学的新闻,包括了新闻发布时间,文章标题和链接。通过改变链接中页数page={}爬取不同页,总共爬取了100页,大约200多条数据。

爬取工具

  • selenium
  • chromeDriver

具体代码

在这里插入图片描述

import time
from selenium import webdriver
import warnings
warnings.filterwarnings("ignore")
import pandas as pd

url='https://search.sina.com.cn/?q=%e5%b1%b1%e4%b8%9c%e5%a4%a7%e5%ad%a6&c=news&from=channel&col=&range=all&source=&country=&size=10&stime=&etime=&time=&dpc=0&a=&ps=0&pf=0&page={}'
driver=webdriver.Chrome()

href_list=[]
topic_list=[]
time_list=[]

# 获取不同页数的网页信息
def next_page(page):
    # 解决加载超时出错
    try:
        driver.get(url.format(str(page)))
        time.sleep(1)
    except TimeoutError:
        return print("TimeoutError")

# 获取网页信息
def get_urls():
    try:
        # 拉动滚轴使页面加载底端的页面元素
        driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')
        time.sleep(2)

        #page = driver.page_source
        #print(page)
        for context in driver.find_elements_by_class_name("box-result.clearfix"):

   
            a=context.find_element_by_tag_name("a")
            href=a.get_attribute("href") #网页链接
            topic=a.text  #标题

            time1=context.find_element_by_tag_name("span").text
            time2=" ".join(time1.split(" ")[1:]) #时间
            

            href_list.append(href)
            topic_list.append(topic)
            time_list.append(time2)
           
    except Exception as err:
        print("未爬取成功:", err)

def main():
    for i in range(1, 100):
        next_page(i)
        print("爬取第{}页内容".format(i))
        get_urls()

    
    dframe = pd.DataFrame({'链接': href_list, '主题': topic_list, '时间': time_list})
    dframe.to_csv('xinlang_urls1.csv', index=False, sep=',', encoding='utf_8_sig')
    driver.quit()
    print("爬取新浪新闻完成!")

if __name__ == '__main__':
    main()

爬取结果

大约200条数据,爬到20多页就获取不到内容了,之后再看看有没有其他方法获得。
csv内容如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值