初学者,勿喷。
目标:教育部官网,数据传输到数据库
环境: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