Python爬取新闻网标题、日期、点击量

最近接触Python爬虫,以爬取学校新闻网新闻标题、日期、点击量为例,记录一下工作进度

目前,感觉Python爬虫的过程无非两步:

Step1.获取网页url(利用Python库函数import urllib2)

Step2.利用正则表达式对html中的字符串进行匹配、查找等操作


自我感觉sublime text2编辑器真心好用,部署Python后不会像WingIDE、notepad++那样存在那么多头疼的小问题,推荐使用


学校新闻网:西南交通大学新闻网--交大新闻


 # -*- coding: UTF-8 -*- 
import urllib2
import sys
import re
import os
#***********fuction define************#
def extract_url(info):
    rege="<li><span class=\"title\"><a href=\"(.*?)\">"#fei tan lan mo shi
    re_url = re.findall(rege, info)
    n=len(re_url)
    for i in range(0,n):
    	re_url[i]="http://news.swjtu.edu.cn/"+re_url[i]
    return re_url

def extract_title(sub_web):
    re_key = "<h4>\r\n                    (.*)\r\n                    </h4>"
    title = re.findall(re_key,sub_web)

    return title

def extract_date(sub_web):
    re_key = "日期:(.*?)    "
    date = re.findall(re_key,sub_web)
    return date

def extract_counts(sub_web):
    re_key = "点击数:(.*?)  "
    counts = re.findall(re_key,sub_web)
    return counts    
#*************main**************#
fp=open('output.txt','w')
content = urllib2.urlopen('http://news.swjtu.edu.cn/ShowList-82-0-1.shtml').read()
url=extract_url(content)
string=""
n=len(url)
print n
for i in range(0,n):
    sub_web = urllib2.urlopen(url[i]).read()
    sub_title = extract_title(sub_web)
    string+=sub_title[0]
    string+='   '
    sub_date = extract_date(sub_web)
    string+="日期:"+sub_date[0]
    string+='   '
    sub_counts = extract_counts(sub_web)
    string+="点击数:"+sub_counts[0]
    string+='\n'
    # print string
print string
fp.close()

技术分享


附:Python爬虫学习系列教程


文章来自:http://blog.csdn.net/u012717411/article/details/46486679
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3