第一个爬虫和测试

Python测试函数的方法之一是用:try……except

复制代码
def gameover(a,b):
    if a>=10 and b>=10 and abs(a-b)==2:
        return True
    if (a>=11 and b<11) or (a<11 and b>=11):
        return True
    return False
try:
    a=gameover(10,11)
    print(a)
except:
    print("Error")
复制代码

 

gameover测试的函数,没传参数的a,b,函数结果是True or False

try:试着执行gameover()函数,正常就执行函数

except:否则 打印'Error'

这里用10,11这一对来测试,结果为:

runfile('D:/新建文件夹/chesi.py', wdir='D:/新建文件夹')
True

程序运行正常且结果正确

若不输入参数,结果应为Error,结果为:

 

打开360搜索20次

用requests()打开360搜索

代码如下:

from requests import *
try:
    for i in range(20):
        r=get("https://www.so.com/")
        r.raise_for_status()
        r.encoding='utf-8'
        print(r)
    print(len(r.text))
    print(len(r.content))
except:
    print("Error")

结果成功显示200 

成功

 

 

 

下面有一段html代码;

<!DOCTYPE html>

<html>

<head>

<meta charset='utf-8'>

<title>菜鸟教程(runoob.com)</title>

</head>\n<body>

<h1>我的第一标题</h1>

<p  id='frist'>我的第一段落。</p>

</body>

</table>

</html>

我们需要做以下要求:

 

我们有以下代码解决:

复制代码
from bs4 import BeautifulSoup
import re
html = BeautifulSoup("<!DOCTYPE html>\n<html>\n<head>\n<meta charset='utf-8'>\n<title>菜鸟教程(runoob.com)</title>\n</head>\n<body>\n<h1>我的第一标题</h1>\n<p  id='frist'>我的第一段落。</p>\n</body>\n</table>\n</html>","html.parser")
print(html.head,"20") 
print(html.body)
print(html.find_all(id="first")) 
r=html.text
pattern = re.findall(u'[\u1100-\uFFFDh]+?',r)
print(pattern)

 

posted @ 2019-05-22 21:37  肖途  阅读(179)  评论(0编辑  收藏  举报