码迷,mamicode.com
首页 > 其他好文 > 详细

第一个爬虫和测试

时间:2019-05-23 09:19:39      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:代码   baidu   ISE   多次   alt   div   内容   中文   百度   

一 完善球赛程序,测试gameover函数的正确性

1.1 未修改之前的乒乓球的gameover函数的代码 

def gameOver(scoreA, scoreB):
    g=scoreA-scoreB
    if (abs(g)==2 and  scoreA> 10 and scoreB> 10) or (g> 0 and scoreA==11) or (g<0 and scoreB==11):
        return True
    elsereturn False
a=input()
b=input()
print(gameover(a,b))

未修改过的上述代码输入多组数据经行测试,显然输出结果与正确结果有些出入

故对以上函数进行修改

1.2 修改后的gameover函数的代码如下:

from math import*
def gameover(scoreA,scoreB):
    g=scoreA-scoreB
    if (abs(g)==2 and scoreA>=10 and scoreB>=10) or (g>0 and scoreA==11 and scoreB!=10)  or (g<0 and scoreB==11 and scoreA!=10):
        return True
    else:
        return False
a=input()
b=input()
print(gameover(a,b))

多次输入测试数据结果如下(输出结果与预想一致结果):

技术图片

二 用requests库的get函数()访问网站20次

2.1 访问百度网站的代码如下:

# -*- coding: utf-8 -*-
"""
Created on Mon May 20 22:19:31 2019

@author: 02豆芽运气
"""

import requests
from bs4 import BeautifulSoup
def getHTMLText(url):
    try:
        r=requests.get(url,timeout=30)
        soup=BeautifulSoup(r.text)
        r.raise_for_status()
        r.encoding=utf_8
        return (r.text,r.status_code,len(r.text),len(soup.p.contents))
    except:
        return""
url=https://www.baidu.com
for i in range(20):
    #for循环调用函数访问网站20次
    print(i)
    print(getHTMLText(url))
    

2.2 执行效果

技术图片

三 对html页面进行一系列的操作

from bs4 import BeautifulSoup
import re
import requests
soup=BeautifulSoup("<!DOCTYPE html><html><head><meta charset=‘utf-8‘><title菜鸟教程(rounoob.com)</title></head><body><h1>我的第一标题</h1><p id=‘first‘>我的第一个段落。</p></body><table border=‘1‘><tr><td>row 1,cell 1</td><td>row 1,cell 2</td></tr><tr><td>row 2,cell 1</td><td>row 2,cell 2</td></tr</table></html>")
print(soup.head,"02")   #打印head标签的内容和我的学号后两位
print(soup.body)      #打印body的内容
print(soup.find_all(id="first"))  #打印id为first的文本
r=soup.text
pattern = re.findall([\u4e00-\u9fa5]+,r)#获取并打印hml页面中的中文字符
print(pattern)

效果:

技术图片

 

第一个爬虫和测试

标签:代码   baidu   ISE   多次   alt   div   内容   中文   百度   

原文地址:https://www.cnblogs.com/2987831760qq-com/p/10892922.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!