学习小记 - Python爬虫 (2) 爬虫闯关系列

偶然发现了一个很有意思的网站爬虫闯关

第一关:

这里是最简单的静态网页爬取,只需要爬到页面中的五个数字然后重复请求URL即可。
但这里有个小bug,到最后的时候会爬到页面下方的另一串数字。

import urllib, urllib2, re

url = 'http://www.heibanke.com/lesson/crawler_ex00/'
plus_str = ''
user_agent = 'Mozilla/4.0 (co,patible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent}
urlp=''
while True:
    try:
        urlp = url+plus_str
        print urlp
        request = urllib2.Request(urlp, headers=headers)
        response = urllib2.urlopen(request)
        content = response.read().decode('utf-8')
        pattern = re.compile('<div class="row">.*?<h3>.*?(\d\d\d\d\d)', re.S)
        plus  = re.findall(pattern, content)
        plus_str = ''
        for i in plus:
            plus_str += str(i)
    except urllib2.URLError, e:
        print e
        print urlp
        break

用bs4和urllib模块实现:(python3.5)

# -*- coding:utf-8 -*-

from urllib.request import urlopen
from urllib.error import HTTPError, URLError
from bs4 import BeautifulSoup
import re

def getTitle(newNum):
    url = 'http://www.heibanke.com/lesson/crawler_ex00/'+newNum
    print ("Calling..." + url)
    page = urlopen(url)
    bsobj = BeautifulSoup(page.read(), "html.parser")
    next_Num = re.findall(r"\d{5}", bsobj.h3.get_text())
    if next_Num == []:
        print ("Finished.")
        return
    return getTitle(next_Num[0])

getTitle('')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值