b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

python:BeautifulSoup 模块使用指南

电脑杂谈  发布时间:2020-03-19 04:02:00  来源:网络整理

beautifulsoup怎么用_用beautifulsoup爬网页_beautifulsoup

BeautifulSoup

官方文档如下介绍:

Beautiful Soup 是一个可以从 HTML 或 XML 文件中提取数据的 Python 库.它无法通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方法.Beautiful Soup 会给你节省数小时或者数天的工作时间.

以下都是在 python2.7 中进行测试的

可以直接使用 pip 安装:

$ pip install beautifulsoup4

beautifulsoup_用beautifulsoup爬网页_beautifulsoup怎么用

BeautifulSoup 不仅支持 HTML 解析器,还支持一些第三方的解析器,如,lxml,XML,html5lib 但是必须安装相应的库。

$ pip install lxml
$ pip install html5lib

Beautiful Soup 的功能非常强大beautifulsoup怎么用,但我们只介绍一直使用的功能。

将一段文档传入 BeautifulSoup 的构造方式,就能得到一个文档的对象, 可以传入一段字符串或一个文件句柄.


>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup("<html><body><p>data</p></body></html>")
>>> soup
<html><body><p>data</p></body></html>
>>> soup('p')
[<p>data</p>]

首先传入一个 html 文档,soup 是获取文档的对象。然后,文档被转换成 Unicode ,并且 HTML 的例子都被转化成 Unicode 编码。然后,Beautiful Soup 选择最合适的解析器来解读这段文档,如果自动指定解析器那么 Beautiful Soup 会选取指定的解析器来解读文档。但是通常最好手动指定解析器,并且使用 requests 与 BeautifulSoup 结合使用,requests 是用于爬取网站源码的一个库beautifulsoup怎么用,此处不再介绍,requests 更多用法请参考 Requests 2.10.0 文档 。


from bs4 import BeautifulSoup
import requests
html = requests.get(‘http://www.jianshu.com/’).content  
soup = BeautifulSoup(html, 'html.parser', from_encoding='utf-8')
result = soup('div')

用beautifulsoup爬网页_beautifulsoup怎么用_beautifulsoup

Beautiful Soup 将复杂 HTML 文档转换成一个复杂的树状结构,每个结点都是 Python 对象,所有对象可以归纳为 4 种: Tag , NavigableString , BeautifulSoup , Comment .

下面是一个示例,带你知道 Beautiful Soup 的常用用法:


import sys  
reload(sys)  
sys.setdefaultencoding('utf-8') 
from bs4 import BeautifulSoup
import requests
html_doc = """
<head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <title>首页 - 简书</title>
</head>
<body class="output fluid zh cn win reader-day-mode reader-font2 " data-js-module="recommendation" data-locale="zh-CN">
<ul class="article-list thumbnails">
  <li class=have-img>
      <a class="wrap-img" href="/p/49728c3ab2"><img src="http://upload-images.jianshu.io/upload_images/2442470-745c6471c6f8258c.jpg?imageMogr2/auto-orient/strip%7CimageView2/1/w/300/h/300" alt="300" /></a>
    <div>
      <p class="list-top">
        <a class="author-name blue-link" target="_blank" href="/users/0af6b163b687">阿随向前冲</a>
        <em>·</em>
        <span class="time" data-shared-at="2016-07-27T07:03:54+08:00"></span>
      </p>
      <h4 class="title"><a target="_blank" href="/p/49728c3ab2"> 只装了这六款软件,工作就高效到有时间逛某宝刷某圈</a></h4>
      <div class="list-footer">
        <a target="_blank" href="/p/49728c3ab2">
          阅读 1830
</a>        <a target="_blank" href="/p/49728c3ab2#comments">
           · 评论 35
</a>        <span> · 喜欢 95</span>
          <span> · 打赏 1</span>
        
      </div>
    </div>
  </li>
</ul>
</body>
"""
soup = BeautifulSoup(html_doc, 'html.parser', from_encoding='utf-8')
# 查找所有有关的节点
tags = soup.find_all('li', class_="have-img")
for tag in tags:
        image = tag.img['src']
        article_user = tag.p.a.get_text()
        article_user_url = tag.p.a['href']      
        created = tag.p.span['data-shared-at']        
        article_url = tag.h4.a['href']
        # 可以在查找的 tag 下继续使用 find_all()
        tag_span = tag.div.div.find_all('span')
        likes = tag_span[0].get_text(strip=True)

BeautifulSoup 主要用来遍历子结点及子节点的属性,通过点取属性的方法只能取得当前文档中的第一个 tag,例如,soup.li。如果想要得到所有的<li> 标签,或是借助名字受到比一个 tag 更多的内容的之后,就必须用到 find_all(),find_all() 方法搜索当前 tag 的所有 tag 子节点,并判定是否依照过滤器的条件find_all() 所接受的参数如下:

find_all( name , attrs , recursive , string , **kwargs )

按 name 搜索: name 参数可以查找所有名字为 name 的 tag,字符串对象会被手动忽略掉:

 soup.find_all("li")

用beautifulsoup爬网页_beautifulsoup怎么用_beautifulsoup

按 id 搜索: 如果包括一个名字为 id 的参数,搜索时会把该参数只是指定名字 tag 的属性来搜索:

 soup.find_all(id='link2')

按 attr 搜索:有些 tag 属性在搜索不能使用,比如 HTML5 中的 data-* 属性,但是可以通过 find_all() 方法的 attrs 参数定义一个字典参数来搜索包括特殊属性的 tag:

 data_soup.find_all(attrs={"data-foo": "value"})

按 CSS 搜索: 按照 CSS 类名搜索 tag 的功能十分实用,但标志CSS 类名的关键字 class 在 Python 中是保留字,使用 class 做参数会导致语法出错.从 Beautiful Soup 的 4.1.1 版本起初,可以通过 class_ 参数搜索有选定 CSS 类名的 tag:

 soup.find_all('li', class_="have-img")

string 参数:通过 string 参数可以搜搜文档中的字符串内容.与 name 参数的可选值一样, string 参数接受 字符串 , 正则表达式 , 列表, True 。 看例子:

beautifulsoup_beautifulsoup怎么用_用beautifulsoup爬网页

 soup.find_all("a", string="Elsie")

recursive 参数:调用 tag 的 find_all() 方法时,Beautiful Soup 会检索当前 tag 的所有子孙节点,如果只想搜索 tag 的直接子节点,可以使用参数 recursive=False .

 soup.find_all("title", recursive=False)

find_all() 几乎是 Beautiful Soup中更常见的搜索方式,也可以使用其简写方式,以下代码等价:

    soup.find_all("a")
    soup("a")

如果只想得到 tag 中包括的文本内容,那么可以用 get_text() 方法,这个方式获得到 tag 中涵盖的所有文版内容包含子孙 tag 中的内容,并将结果成为 Unicode 字符串返回:

    tag.p.a.get_text()

如果想看更多内容,请参考 (中文文档)。


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-144657-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      热点图片
      拼命载入中...