python中使用lxml与cssselect爬取电子书及链接

---恢复内容开始---

在浏览这个网站(http://blog.jobbole.com/29281/)时,发现电子书不错。

 

就想download下来,也正好在学习爬虫,以下就用lxml及cssselect的方式下载下来,也当是个小练习。

1.download函数

import lxml.html

def download(url,user_agent='wswp',num_retires=2):
    print 'Downloading:' ,url
    headers = {'User-agent': user_agent}
    request = urllib2.Request(url,headers=headers)
    try:
        html = urllib2.urlopen(request).read()
    except urllib2.URLError as e:
        print "Downloading error:", e.reason
        html = None
        if num_retires>0:
            if hasattr(e,'code') and 500<= e.code <600:
                return download(url, user_agent,num_retires-1)
    return html

 

2.抓取数据(注意加粗的cssselect的使用)

if __name__ == "__main__":
    url = 'http://blog.jobbole.com/29281/'
    html = download(url)
    for i in itertools.count(1):
        tree = lxml.html.fromstring(html)
        try:
            td = tree.cssselect('ol > li > a')[i]
            book = td.text_content()
            href = td.get('href')
            print book,href
        except:
            break

数据抓取完毕。

转载于:https://www.cnblogs.com/bigbrother/p/6545883.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值