爬取教育部新闻标题

初学者,勿喷。

目标:教育部官网,数据传输到数据库

环境:python3.6

需要模块:urllib,re,pymysql

思路:通过正则匹配,匹配出新闻标题所在位置。


```python
#hard = 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134'

from urllib import request
import re
import pymysql


k=[]
p=[]
sum=0
cum=0

a="index_"
b=".html"
for d in range(11):
    c=a+str(d)+b
    if d==0:
        url='http://www.moe.gov.cn/jyb_xwfb/gzdt_gzdt/'
    else:
        url='http://www.moe.gov.cn/jyb_xwfb/gzdt_gzdt/'+c




#url='http://www.moe.gov.cn/jyb_xwfb/gzdt_gzdt/'
    head={}
    head['User-Agent']='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134'
    req=request.Request(url,headers=head)
    response=request.urlopen(req)
    html=response.read().decode('utf-8')

    print(html)


    result = re.findall(".*title=(.*)<span>.*",html)
    results = re.findall(".*<span>(.*)</span></li>.*",html)
    for x in result:
        k.append(x)
        sum+=1
    for z in results:
        p.append(z)
        cum+=1
print(k,p)
print(sum,cum)
connent = pymysql.connect(host='数据库地址', user='用户名', passwd='密码', db='数据库名称', charset='utf8')

cursor = connent.cursor()
f=0
while 1:
    sql="insert into news(new_Title,new_Time) values("+"'"+k[f]+"'"+","+"'"+p[f]+"'"+")"
    cursor.execute(sql)
    connent.commit()
    f=f+1
    if f==220:
        break

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值