python编程快速上手 第11章实践项目答案

11.3 2048

2048是一个简单的游戏,通过箭头向上、下、左、右滑动,让滑块合并。实际上,你可以通过一遍遍的重复‘上下左右’模式,获得相当高的分数。编写一个程序,打开http://gabrielecirulli.github.io/2048/上的游戏,不断发送上下左右按键,自动玩游戏

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
browser.get('https://gabrielecirulli.github.io/2048/')
htmlElem = browser.find_element_by_tag_name('html')
for i in range(100):
    htmlElem.send_keys(Keys.UP)
    htmlElem.send_keys(Keys.LEFT)
    htmlElem.send_keys(Keys.RIGHT)
    htmlElem.send_keys(Keys.DOWN)
    print('done!')

11.4链接验证

编写一个程序,对给定的网页URL,下载该页面的所有链接的页面。程序应该标记出所有具有404‘NotFound'状态码的页面,将它们作为坏链接输出

import requests,os,bs4
url = 'https://www.scut.edu.cn/new/'
os.makedirs('11.11.4',exist_ok=True)
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, "html.parser")
comicElem = soup.select('a[href]')
for i in range (0,len(comicElem)-1):
    if comicElem[i].get('href').startswith('http:'):
        dlurl=comicElem[i].get('href')
    elif comicElem[i].get('href').startswith('#'):
        continue
    else:
        dlurl='https://www.scut.edu.cn'+comicElem[i].get('href')
    temp = requests.get(dlurl)
    if temp.status_code == 404:
        print(dlurl + 'is 404')
    else:
        tempFile = open('11.11.4\\'+str(i)+'.txt','wb')
        for chunk in temp.iter_content(100000):
            tempFile.write(chunk)
        tempFile.close()

猜你喜欢

转载自blog.csdn.net/u014221647/article/details/81018025
今日推荐