在跟着老师做了一遍之后开始决定自己做一遍,顺带多查查多看看。
Python 内置的 HTTP 请求库,也就是说我们不需要额外安装即可使用,它包含四个模块:
使用urlopen()
函数模拟浏览器打开一个网页并将网页的信息存储返回一个HTTPResposne
类型的对象。
import urllib.request
url = "www.baidu.com"
response = urllib.request.urlopen(url)
print(response.read().decode(‘utf-8‘))
设置请求网页时的参数
打开网页时可以使用多种参数来实现各种强大的功能
# timeout 参数可以设置超时时间,单位为秒,意思就是如果请求超出了设置的这个时间还没有得到响应,就会抛出异常,单位为毫秒
response = urllib.request.urlopen(url, timeout=0.1)
HTTPResposne
类型的对象具有多种方法和属性:
使用Request()
函数封装一个对象作为请求的内容,将头文件、字节流编码格式等信息封装进去。
请求文件的封装:有两种方式,一种是直接添加,一种是使用函数。
# ——————直接添加———————这种要求加入前要以字典的方式打包好
url = "http://httpbin.org/post"
# 从浏览器获得的头部文件
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36 Edg/81.0.416.62"} # 键值对
# 字节流编码格式信息,需要使用`urllib.parse`模块里的`urlencode()`方法将参数字典转换为字符串,并且指定编码格式
data = bytes(urllib.parse.urlencode({‘name‘:‘eric‘}), encoding="utf-8")
# 封装,包含了网址信息,头部文件,编码格式,请求方式,这种是直接加入
req = urllib.request.Request(url = url, data=data, headers=headers, method = "POST")
# ——————使用函数添加——————这种只要以字符串的方式准备好即可,首参就是要添加的属性,感觉更为方便
cookies = r‘JSESSIONID=xxxxxxxxxxxxxxxxxxxxxx; iPlanetDirectoryPro=xxxxxxxxxxxxxxxxxx‘
req.add_header(‘cookie‘, cookies)
使用封装好的请求文件进行网页请求
# 使用该请求对象进行请求
response = urllib.request.urlopen(req)
Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:Tag
, NavigableString
, BeautifulSoup
, Comment
。
bs = BeautifulSoup(html, "html.parser") # html是从网页抓取的源代码
# 1.Tag:打印后面参数第一次出现的标签及其内容,BS4中的“Tag”元素
print(bs.title)
print(bs.a)
print(type(bs.a))
# 2.NavigableString: 将标签里的字符串进行输出
print(bs.title.string)
print(type(bs.title.string))
# 3.字典,拿到标签的属性,字典类型
print(bs.a.attrs)
print(type(bs.a.attrs))
# 4.BeautifulSoup 表示整个文档
print(bs)
print(type(bs))
5.Comment 是一个特殊的是一个特殊的NavigableString,输出的内容不包括注释符号
print(bs.a.string)
print(type(bs.a.string))
print(bs.head.contents) # 获取Tag的所有子节点,返回一个list
print(bs.head.contents[1])
findall()
函数# 字符串过滤:找出所有与字符串完全匹配的标签及其内容
t_list = bs.find_all("a")
# 正则表达式搜索:使用search()方法来匹配标签及其内容
t_list = bs.find_all(re.compile("a"))
# 方法:传入一个函数(方法),根据函数的要求来搜索
def name_is_exists(tag): # 传入一个标签,返回标签的name属性
return tag.has_attr("name")
t_list = bs.find_all(name_is_exists)
# 参数:传入各种参数来查找
t_list = bs.find_all(id = "head")
t_list = bs.find_all(text = "hao123")
t_list = bs.find_all(text = ["hao123", "地图", "贴吧"])
# 正则表达式:怎么编辑正则表达式见下一章
t_list = bs.find_all(text = re.compile("\d"))
#限定查找个数
t_list = bs.find_all("a", limit = 3)
# 通过标签查找
t_list = bs.select(‘title‘)
# 通过类名查找
t_list = bs.select(‘.mnav‘)
# 通过ID来查找
t_list = bs.select(‘#u1‘)
# 通过属性来查找
t_list = bs.select("a[class=‘bri‘]")
# 通过子标签来查找
t_list = bs.select("head > title")
是用来简洁表达一组字符串的表达式。
原文:https://www.cnblogs.com/Za-Ya-Hoo/p/12768793.html