|
本帖最后由 Tinken 于 2020-10-2 12:11 编辑
有了requests就可以像网页发送请求了,通过request.text得到网页内容
但是,我们还需要从复杂的网页内容中提取出有用或者说我们需要的数据,这里需要学习另一个库:Beautiful Soup
Beautiful Soup
是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时甚至数天的工作时间.
Beautiful Soup 4.4.0 文档:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
第一步:安装Beautiful Soup 4.4.0pip install beautifulsoup4
安装解码器(可选,也可以不安装)pip install lxml
看来文件比较小巧,很快就安装完成了。这个我喜欢^.^简单使用
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- # @ClassName test3
- # @Description TODO
- # @Author lanlo
- # @Date 2020-10-02 2:26
- # @Version 1.0
- import requests
- from bs4 import BeautifulSoup
- url = "http://www.vrpip.com/forum.php?mod=viewthread&tid=62&extra="
- res = requests.get(url)
- # 查看返回数据对象
- print(type(res))
- # 打印响应状态码
- print(res.status_code)
- # 定义编码
- res.enconding = "utf-8"
- # 将获得的html文档传入BeautifulSoup的构造方法
- soup=BeautifulSoup(res.text)
- # 使用prettify()美化后输出
- print(soup.prettify())
复制代码
深入学习(放弃了,内容和规则实在太多了 )- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- # @ClassName test3
- # @Description TODO
- # @Author lanlo
- # @Date 2020-10-02 2:26
- # @Version 1.0
- import requests
- from bs4 import BeautifulSoup
- url = "http://www.vrpip.com/forum.php?mod=viewthread&tid=62&extra="
- res = requests.get(url)
- # 查看返回数据对象
- print(type(res))
- # 打印响应状态码
- print(res.status_code)
- # 定义编码
- res.enconding = "utf-8"
- html=res.text
- # 将获得的html文档传入BeautifulSoup的构造方法,指定解码器:html.parser
- soup = BeautifulSoup(html, "html.parser")
- # 打印html或者代码中的:<title>标签
- print(soup.title)
- # 打印html或者代码中的:<span>,此方式只会打印页面第一<span>标签内容
- print(soup.span)
- # 打印<span>标签的“class”属性名(如span的属性:class = 'xg1',打印结果:['xg1'])
- print(soup.span["class"])
- # .attrs会打印出<body>的所有属性:id、class...
- print(soup.span.attrs)
- # 打印所有<span>标签
- print(soup.find_all("span"))
- # 打印<body>标签的"id"属性值
- print(soup.body["id"])
- print("------------ 我是分割线 ---------------")
- # 打印html或者代码中的:<title>标签中的:字符串
- print(soup.title.string)
- # 打印html或者代码中的,<head>中包含的所有标签内容
- print(soup.head.contents)
- # 打印html或者代码中的,<head>中包含的第二个标签内容,第一个是[0]
- print(soup.head.contents[1])
- # 循环打印html或者代码中的,<head>中包含标签内容
- for child in soup.head.children:
- print(child)
- # .
- # .
- # .
- # .
- # .
- # .
- # .
- # 不学了,这解码器规则太多了,一下子看完也不一定记得住
- # 记住文档地址:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
- # 后面分析页面结构,提取页面内容在查文档,边使用边学
复制代码
|
|