鱼C论坛

 找回密码
 立即注册
查看: 3378|回复: 0

[技术交流] python爬虫进阶beautifulsoup【0】

[复制链接]
发表于 2017-7-9 13:16:43 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

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

x
本帖最后由 MSK 于 2017-7-9 23:01 编辑

推荐阅读:BeautifulSoup对象



写爬虫觉得正则表达式太难?不妨试试BeautifulSoup!!!


Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库,
首先你需要一些 html 基础




1.安装


pip install  beautifulsoup4



ps:我们使用的版本是BeautifulSoup4




我就喜欢用pip




2.导入


from bs4 import BeautifulSoup



3.beautifulsoup 初窥


先给出一段html代码,以后会经常用到


  1. html = """
  2. <html><head><title>The Dormouse's story</title></head>
  3. <body>
  4. <p class="title"><b>The Dormouse's story</b></p>

  5. <p class="story">Once upon a time there were three little sisters; and their names were
  6. <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
  7. <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
  8. <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
  9. and they lived at the bottom of a well.</p>'''
复制代码





导入模块、生成BeautifulSoup对象

  1. from bs4 import BeautifulSoup
  2. soup = BeautifulSoup(html_doc,'html.parser')
复制代码


获取<title>标签


  1. soup.title
  2. #<title>The Dormouse's story</title>
复制代码





获取<title>标签的name


  1. soup.title.name
  2. #title
复制代码




看,比正则表达式简单吧





获取<title>标签的文本


  1. soup.title.string
  2. #"The Dormouse's story"
  3. soup.title.text
  4. #"The Dormouse's story"
复制代码





获取<p>标签的class


  1. soup.p['class']
  2. #['title']
复制代码





找出所有<a>标签


  1. soup.find_all('a')
  2. # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
  3. #  <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,
  4. #  <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
复制代码






找出id为link3的标签



  1. soup.find(id="link3")
  2. # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
复制代码





这篇帖子先让大家对BeautifulSoup有个了解

未完待续!!!

评分

参与人数 2鱼币 +5 收起 理由
小甲鱼 + 3
康小泡 + 2

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 18:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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