python学习笔记(25)——cninfo网下载多页关键字公告(selenium应用)

代码练习:啰嗦解释版本

from selenium import webdriver#引进selinium库
import time
import re#引入re库
#定义函数
def cninfo(keyword):
    #selenium库模拟浏览器
    url='http://www.cninfo.com.cn/new/fulltextSearch?notautosubmit=&keyWord='+keyword#找规律,定义网址
    chrome_options=webdriver.ChromeOptions()#定义chrome_options执行打开谷歌浏览器
    chrome_options.add_argument('--headless')#定义chrome_options把隐藏窗口命令加入浏览器操作
    browser=webdriver.Chrome(options=chrome_options)#定义浏览器命令browser执行chrome_options命令
    browser.get(url)#browser执行浏览器获取网址命令
    time.sleep(5)#时间库执行停顿5秒
    data=browser.page_source#定义data,执行浏览器获取源码命令
    p_count='<span class="total-box" style="">共 (.*?) 条 当前显示1-10条</span>'#定义p_count,提取公告总数
    count=re.findall(p_count,data)[0]#把提取的公告总数赋予count,此处用findall()得到的是一个列表,所以要加[0],提取元素
    pages=int(int(count)/10)  # 通过公式得到页数,先把findall()得到的数据转为整型,再把进行运算后的数据去小数转换为整数

    datas=[]#创建一个新列表datas,来装全部源码数据
    datas.append(data)#把获取的第一页源代码储存到datas列表中
    for i in range(pages):
        browser.find_element_by_xpath('//*[@id="fulltext-search"]/div/div/div[2]/div[4]/div[2]/div/button[2]').click()#遍历页数点击下一页
        time.sleep(2)#防止页面没有加载完成,停顿2秒
        data=browser.page_source#每点击一次,获取一次源码
        datas.append(data)#把每次的源码加入datas列表中
        time.sleep(1)#防止页面没有加载完成,停顿1秒
    alldata=''.join(datas)#把装有全部源码的列表转化为字符串
    browser.quit()  # 关闭模拟浏览器
    #正则提取内容
    p_title = '<span title="" class="r-title">(.*?)</span>'#提取标题
    p_href = '<a target="_blank" href="(.*?)" data-id=".*?" data-orgid=.*?" data-seccode=".*?" class="ahover">'#提取网址
    p_date = '<td rowspan="1" colspan="1" class="el-table_1_column_3 is-left "><div class="cell"><span class="time">(.*?)</span>'#提取时间
    title = re.findall(p_title,alldata,re.S)#使用re.S,将“\n”当做一个普通的字符,在整体中进行匹配
    href = re.findall(p_href,alldata)#不使用re.S参数,只在每一行内进行匹配,如果一行没有,就换下一行重新开始
    date = re.findall(p_date,alldata,re.S)
    # print(title)#通过观察需要清除<>内容
    # print(href)#通过观察,网址需要加前缀http: // www.cninfo.com.cn /,去掉文中amp;
    # print(date)#通过观察,日期需要清除换行符,空格以及部分带时间的格式
    #遍历标题清洗数据
    for i in range(len(title)):
        title[i]=re.sub('<.*?>', '', title[i])#清理title里多余的<>内容
        href[i]='http://www.cninfo.com.cn' + href[i]#加网络前缀
        href[i]=re.sub('amp;', '', href[i])#提取的网址多出的amp;清理掉
        date[i]=date[i].strip()#提取的日期,清除换行符,空格以及部分带时间的格式
        date[i]=date[i].split(' ')[0]#以空格为分隔符,取第一个元素日期
        print(str(i+1)+'.'+title[i]+'-'+date[i])#打印格式代码
        print(href[i])
#调用自定义函数
keywords=['纾困']
for i in keywords:
    cninfo(i)


运行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值