请选择 进入手机版 | 继续访问电脑版

VRPIP 虚拟化平台

 找回密码
 注册VRPIP
搜索
热搜: 活动 交友 discuz
查看: 21588|回复: 0

小白 学pyton 爬虫二

[复制链接]

8

主题

11

帖子

55

积分

注册会员

Rank: 2

积分
55
发表于 2020-10-2 02:11:14 | 显示全部楼层 |阅读模式
本帖最后由 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

看来文件比较小巧,很快就安装完成了。这个我喜欢^.^简单使用
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-

  3. # @ClassName test3
  4. # @Description TODO
  5. # @Author lanlo
  6. # @Date 2020-10-02 2:26
  7. # @Version 1.0

  8. import requests
  9. from bs4 import BeautifulSoup

  10. url = "http://www.vrpip.com/forum.php?mod=viewthread&tid=62&extra="
  11. res = requests.get(url)

  12. # 查看返回数据对象
  13. print(type(res))

  14. # 打印响应状态码
  15. print(res.status_code)
  16. # 定义编码
  17. res.enconding = "utf-8"

  18. # 将获得的html文档传入BeautifulSoup的构造方法
  19. soup=BeautifulSoup(res.text)
  20. # 使用prettify()美化后输出
  21. print(soup.prettify())
复制代码

深入学习(放弃了,内容和规则实在太多了
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-

  3. # @ClassName test3
  4. # @Description TODO
  5. # @Author lanlo
  6. # @Date 2020-10-02 2:26
  7. # @Version 1.0

  8. import requests
  9. from bs4 import BeautifulSoup


  10. url = "http://www.vrpip.com/forum.php?mod=viewthread&tid=62&extra="
  11. res = requests.get(url)

  12. # 查看返回数据对象
  13. print(type(res))

  14. # 打印响应状态码
  15. print(res.status_code)
  16. # 定义编码
  17. res.enconding = "utf-8"
  18. html=res.text

  19. # 将获得的html文档传入BeautifulSoup的构造方法,指定解码器:html.parser
  20. soup = BeautifulSoup(html, "html.parser")

  21. # 打印html或者代码中的:<title>标签
  22. print(soup.title)
  23. # 打印html或者代码中的:<span>,此方式只会打印页面第一<span>标签内容
  24. print(soup.span)
  25. # 打印<span>标签的“class”属性名(如span的属性:class = 'xg1',打印结果:['xg1'])
  26. print(soup.span["class"])
  27. # .attrs会打印出<body>的所有属性:id、class...
  28. print(soup.span.attrs)
  29. # 打印所有<span>标签
  30. print(soup.find_all("span"))
  31. # 打印<body>标签的"id"属性值
  32. print(soup.body["id"])

  33. print("------------ 我是分割线 ---------------")
  34. # 打印html或者代码中的:<title>标签中的:字符串
  35. print(soup.title.string)
  36. # 打印html或者代码中的,<head>中包含的所有标签内容
  37. print(soup.head.contents)
  38. # 打印html或者代码中的,<head>中包含的第二个标签内容,第一个是[0]
  39. print(soup.head.contents[1])
  40. # 循环打印html或者代码中的,<head>中包含标签内容
  41. for child in soup.head.children:
  42.     print(child)

  43. # .
  44. # .
  45. # .
  46. # .
  47. # .
  48. # .
  49. # .
  50. # 不学了,这解码器规则太多了,一下子看完也不一定记得住
  51. # 记住文档地址:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
  52. # 后面分析页面结构,提取页面内容在查文档,边使用边学


复制代码








本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?注册VRPIP

x
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册VRPIP

本版积分规则

快速回复 返回顶部 返回列表