Python爬虫和函数调试

一:函数调试

用之前学过的try···except进行调试

测试球赛的GameOver函数

def gameover(setA,setB):
    if setA==3 or setB==3:
        return True
    else:
        return False
try:
    a=gameover(3,4)
    print(a)
except:
    print("Error")

输出True

二:Python爬虫

requests库是一个简洁且简单的处理HTTP请求的第三方库。

get()是对应与HTTP的GET方式,获取网页的最常用方法,可以增加timeout=n 参数,设定每次请求超时时间为n秒

text()是HTTP相应内容的字符串形式,即url对应的网页内容

content()是HTTP相应内容的二进制形式

用requests()打开搜狗主页20次

import requests
try:
    for i in range(20):
        r=requests.get("https://123.sogou.com",timeout=30)
        print(type(r))
        print(r.text)
except:
    print('error')

三、

import re
from bs4 import BeautifulSoup
html = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>

<h1>我的第一个标题</h1>
<p id="first">我的第一个段落。</p>
<table border="1">
<tr>
<td>row 1, cell 1<\td>
<td>row 1, cdll 2<\td>
<\tr>
<tr>
<td>row 2, cell 1<\td>
<td>row 2, cell 2<\td> 
<\tr>
<\table>
<\body>
<\html>
"""
soup = BeautifulSoup(html,"html.parser")
print(soup.prettify())
print("(B).该html的body标签内容为\n{}".format(soup.body.prettify()))

该html的body标签内容为
<body>
<h1>
我的第一个标题
</h1>
<p id="first">
我的第一个段落。
</p>
<table border="1">
<tr>
<td>
row 1, cell 1&lt; d&gt;
<td>
row 1, cdll 2&lt; d&gt;
&lt; r&gt;
<tr>
<td>
row 2, cell 1&lt; d&gt;
<td>
row 2, cell 2&lt; d&gt;
&lt; r&gt;
&lt; able&gt;
&ltody&gt;
&lt;\html&gt;
</td>
</td>
</tr>
</td>
</td>
</tr>
</table>
</body>

posted @ 2019-05-22 01:12  Coylin  阅读(229)  评论(0编辑  收藏  举报