[Python Challenge通关]第4关 follow the chain

chainsaw

挑战地址,点我

分析

点击图片跳转到新的网页:

and the next nothing is 44827

当前页面的 url: http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345

这应该是一个类似链表的结构,用 44827 替换当前网页的 url:

and the next nothing is 45439

用代码实现,看看最终会怎么样。这里需要使用 urllib.request 来发起 http 请求,获取返回的内容,然后使用正则表达式匹配 nothing 的值,替换掉原来的 nothing 循环下去。

#!/usr/bin/env/ python3

import urllib.request
import re
import time

baseURL = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s"

# nothing 初始值
nothing = "12345"

while True:
    url = baseURL % nothing
    with urllib.request.urlopen(url, timeout=30) as f:
        response = f.read().decode("utf-8")
        print(response)
        # 使用正则表达式匹配到 nothing 的值,如果匹配到,替换 nothing,匹配不到,退出循环
        result = re.search(r"\d+", response)
        if result:
            nothing = result.group()
        else:
            break
    # 暂停 1s,请求不要太频繁
    time.sleep(1)

运行了一会儿,输出如下内容:

and the next nothing is 44827
and the next nothing is 45439
<font color=red>Your hands are getting tired </font>and the next nothing is 94485
...省略很多行
and the next nothing is 3875
and the next nothing is 16044
Yes. Divide by two and keep going.

根据提示,nothing 的当前值是 16044,把 nothing 的值设置为 str(16044/2) 继续运行,又输出了如下内容:

and the next nothing is 25357
and the next nothing is 89879
... 省略很多行
and the next nothing is 82682
There maybe misleading numbers in the
text. One example is 82683. Look only for the next nothing and the next nothing is 63579

页面内容中出现了两次数字,根据提示应该取后面的数字,需要修改正则表达式,使得匹配规则更加精确。

#!/usr/bin/env/ python3

import urllib.request
import re
import time

baseURL = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=%s"

# nothing 初始值
nothing = str(63579)

while True:
    url = baseURL % nothing
    with urllib.request.urlopen(url, timeout=30) as f:
        response = f.read().decode("utf-8")
        print(response)
        # 使用正则表达式匹配到 nothing 的值,如果匹配到,替换 nothing,匹配不到,退出循环
        result = re.search(r"the next nothing is (\d+)", response)
        if result:
            nothing = result.group(1)
        else:
            break
    # 暂停 1s,请求不要太频繁
    time.sleep(1)

继续运行,又输出了如下内容:

and the next nothing is 37278
and the next nothing is 53548
...省略很多行
and the next nothing is 52899
and the next nothing is 66831
peak.html

最后输出了 peak.html,这就是下一关的入口了http://www.pythonchallenge.com/pc/def/peak.html

参考资源:

  1. urllib.request 官方文档
  2. Python 爬虫介绍
  3. python 正则表达式菜鸟教程
  4. 正则表达式30分钟入门教程
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值