网络爬虫

来源:互联网 发布:小世界网络 netlogo 编辑:程序博客网 时间:2024/06/04 06:40

Python爬虫可以使用scrapy框架,不过开始学习爬虫还是使用urllib2库为好,这样可以熟悉爬虫的整个流程,页面的解析使用XPath比较方便,要比使用正则匹配更灵活和简洁一些。下面抓取学校新闻标题为例:


#-*- encoding=utf-8 -*-
import urllib,urllib2
from lxml import etree
import re
url='http://www.ss.pku.edu.cn/index.php/admission'
request=urllib2.Request(url)
html=urllib2.urlopen(request)

#print html.read().decode('utf-8')
response=html.read()
print response


#使用正则表达式匹配,也可得到想要的结果

#pattern=re.compile(r'<p class="info-title">(.*?)</p>',re.S)

#li=re.findall(pattern,response.decode('utf-8'))#decode()解决乱码问题

#for i in li:
#    print i


#使用xpath得到结果,相比正则表达式更简单
selector=etree.HTML(response)
items=selector.xpath('//div[@class="info-list"]/ul/li')
for item in items:
for i in item.xpath('a/@href'):
print i






2 0
原创粉丝点击