zoukankan      html  css  js  c++  java
  • Python 爬虫闯关(第一关)

    在学习爬虫时,遇到了一个有意思的网站,这个网站设置了几个关卡,需要经过爬虫进行闯关,随着关卡的网后,难度不断增加,在闯关的过程中需要学习不同的知识,你的爬虫水平也自然随之提高。

    今天我们先来第一关,访问http://www.heibanke.com/lesson/crawler_ex00/

    第一关

    按照提示,我们把数字放到地址栏的后面,再次进行访问:

    再次访问

    发现,还要再用新的数字放在地址栏进行访问,我们可以猜测了,第一关是将页面出现的数字填写到当前 url 的尾部进行访问,然后会得到一个新的数字,再用它替换 url 中的尾部数字,这样不断循环往复,直到页面出现成功标识:

    中间环节页面

    那么思路也有了:

    1. 解析页面中的数字;
    2. 将数字拼接成新的 URL;
    3. 访问新的 URL,重复第 1 步;
    4. 直至页面没有数字可以解析到!

    逻辑比较简单,这里我们直接上代码了:

    BeautifulSoup 实现

    # coding=utf-8
    
    import requests, bs4, re
    
    url = 'http://www.heibanke.com/lesson/crawler_ex00/'
    
    while True:
        # download the page
        print("forward to page %s ..." % url)
        response = requests.get(url)
        print("the return code : " + str(response.status_code))
    
        soup = bs4.BeautifulSoup(response.text, "html.parser")
    
        # 获取页面数字
        comic = soup.select('h3')
        print(comic[0].getText())
        number = re.findall("d+", comic[0].getText())
        if number == []:
            print('The end.')
            break;
        else:
            url = 'http://www.heibanke.com/lesson/crawler_ex00/' + number[0] # 拼接新地址
    

    程序运行结果

    selenium 实现

    # coding=utf-8
    
    import requests, re
    from selenium import webdriver
    
    url = 'http://www.heibanke.com/lesson/crawler_ex00/'
    
    browser = webdriver.Firefox()
    
    while True:
        # download the page
        print("Forward to page %s ..." % url)
        browser.get(url)
        elem = browser.find_element_by_tag_name('h3')
    
        # get the url of the for the next page
        print(elem.text)
        number = re.findall("d+", elem.text)
        if number == []:
            print('The end.')
            browser.quit()
            break;
        else:
            url = 'http://www.heibanke.com/lesson/crawler_ex00/' + number[0] # 拼接新地址
    

    到这里我们才能看到最终成功的页面长这样:

    最终页面

    好了,第一关相对来说比较容易,下次我们来搞一下第二关,又兴趣的可以自己先上手攻取下了~


    如果觉得有用,欢迎关注我的微信,一起学习,共同进步,不定期推出赠书活动~

    你的关注是对我最大的鼓励!

    最近搜集到慕课网视频,视频内容涵盖 Python、Java、PHP、前端、小程序、算法、架构、数据库等等!关注本公众号,后台回复「慕课网」即可获取下载地址。

  • 相关阅读:
    Hanoi塔
    采药
    进制转换(大数)
    Load Balancing with NGINX 负载均衡算法
    upstream模块实现反向代理的功能
    epoll
    在nginx启动后,如果我们要操作nginx,要怎么做呢 别增加无谓的上下文切换 异步非阻塞的方式来处理请求 worker的个数为cpu的核数 红黑树
    粘性会话 session affinity sticky session requests from the same client to be passed to the same server in a group of servers
    负载均衡 4层协议 7层协议
    A Secure Cookie Protocol 安全cookie协议 配置服务器Cookie
  • 原文地址:https://www.cnblogs.com/hoxis/p/9706190.html
Copyright © 2011-2022 走看看