BeautifulSoup 有何用途

如果我们需要通过脚本来抓取网络中的数据时,使用传统的字符解析等方法时是非常低效的,而BeautifulSoup则可以方便的通过接口来获取标签中所想要得到的数据。主要用在解析静态页面的数据,如果设计到动态产生的内容,则还需要结合其他库模块来一起配合使用,如selenium模块等。

安装方法

pip install beautifulsoup4

详情可以见中文文档的地址:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/#id5

使用方法

在抓取网页数据时,一般和 requests 库一起使用,如下:

import requests
from bs4 import BeautifulSoup url = 'http://tianqi.com/hangzhou/7'
HEADERS = {'User-Agent':'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11'} req = requests.get(url, headers=HEADERS, timeout=5)
soup = BeautifulSoup(req.text, "html.parser")

假如在request的请求中出现以下连接问题并且你的网路处于代理模式时,则需要在get接口中将代理的IP和端口填写上

抛出异常:
Connection Aborted Error(10060 ' A connection attempt failed becvause the connected party did not properly respond after a period of time, or established a connection failed because connected host has failed to respond' 解决方法:
PROXY = {'http': 'http://xx.xxx.xx.xx:xxxx'} 替换为代理IP和端口
req = requests.get(url, headers=HEADERS, proxies=PROXY, timeout=5)
soup = BeautifulSoup(req.text, "html.parser") timeout 参数是自己可以设定的连接超时时间,单位:秒

下文的小程序是用于获取一个城市7天的天气情况

爬取的网页地址是:http://tianqi.com/hangzhou/7

其中的 hangzhou 可以替换为其他任何城市

import requests
from bs4 import BeautifulSoup
import sys
HEADERS = {'User-Agent':'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11'} def get_soup_from_link(url):
req = requests.get(url, headers=HEADERS, timeout=5)
return BeautifulSoup(req.text, "html.parser") def get_weather_report_list(weather_info):
weather_report_list = [] for group in weather_info:
detail_info = {}
txt = group.find_all(class_='txt')
detail_info['date'] = group.find('dl').get_text()
detail_info['description'] = group.find(class_='temp').get_text()
detail_info['temperature'] = txt[0].get_text()
detail_info['wind'] = txt[1].get_text() weather_report_list.append(detail_info) return weather_report_list def print_day_weather(weather_list, city):
print('City: ' + city)
for weather in weather_list:
print(weather['date'] + '\t' + weather['description'] + '\t' + weather['temperature'] + '\t' + weather['wind']) def main():
print(sys.argv) city = 'hangzhou'
if len(sys.argv) == 1:
city = 'hangzhou'
elif len(sys.argv) == 2:
city = sys.argv[1].lower()
else:
print('Usage: python Weather.py city_name\n city_name: hangzhou, shanghai, ...')
return weather_url = 'http://tianqi.com/' + city + '/7'
soup = get_soup_from_link(weather_url)
weather_table_day7 = soup.find_all(class_='table_day7')
weather_report_list = get_weather_report_list(weather_table_day7)
print_day_weather(weather_report_list, city) if __name__ == '__main__':
main()

通过Chrome F12,我们可以看到我们需要解析的标签数据如下,他们都在 class="table_day7 tag" 或者 class="table_day7" 中

<dl class="table_day7 tbg">
<dl>01月26日</dl>
<dd class="week">今天</dd>
<dd class="air">
<b style="background-color:#79b800;" title="空气质量:优">优</b>
</dd>
<dd class="img">
<img src="http://pic9.tianqijun.com/static/tianqi2018/ico2/b15.png"/>
</dd>
<dd class="temp">雪</dd>
<dd class="txt">
-1℃ ~ <b>1</b>

</dd>
<dd class="txt">东北风 3级</dd>
</dl>
...
...
<dl class="table_day7 ">
<dl>02月01日</dl>
<dd class="week">星期四</dd>
<dd class="air">
<b style="background-color:#79b800;" title="空气质量:优">优</b>
</dd>
<dd class="img">
<img src="http://pic9.tianqijun.com/static/tianqi2018/ico2/b1.png"/>
</dd>
<dd class="temp">多云</dd>
<dd class="txt">
-3℃ ~ <b>6</b>

</dd>
<dd class="txt">东北风 1级</dd>
</dl>

因此,我们需要先找到这些标签块,通过find_all(class_='table_day7')方法,我们可以很快找到这些内容

weather_url = 'http://tianqi.com/' + city + '/7'
soup = get_soup_from_link(weather_url)
weather_table_day7 = soup.find_all(class_='table_day7') find_all 返回的是一个列表,里面包含的是所有找到的匹配项。
入参使用带下划线的class,是因为class是python中的关键字,所以用class_来进行代替 下面就是我们暂时得到的数据结果: [<dl class="table_day7 tbg">
<dl>01月26日</dl>
<dd class="week">今天</dd>
<dd class="air"><b style="background-color:#79b800;" title="空气质量:优">优</b></dd>
<dd class="img"><img src="http://pic9.tianqijun.com/static/tianqi2018/ico2/b15.png"/></dd>
<dd class="temp">雪</dd>
<dd class="txt">-1℃ ~ <b>1</b>℃</dd>
<dd class="txt">东北风 3级</dd>
</dl>, <dl class="table_day7 tbg">
<dl>01月27日</dl>
<dd class="week">明天</dd>
<dd class="air"><b style="background-color:#79b800;" title="空气质量:优">优</b></dd>
<dd class="img"><img src="http://pic9.tianqijun.com/static/tianqi2018/ico2/b15.png"/></dd>
<dd class="temp">雪</dd>
<dd class="txt">-2℃ ~ <b>0</b>℃</dd>
<dd class="txt">北风 2级</dd>
</dl>, <dl class="table_day7 tbg">
<dl>01月28日</dl>
<dd class="week">后天</dd>
<dd class="air"><b style="background-color:#79b800;" title="空气质量:优">优</b></dd>
<dd class="img"><img src="http://pic9.tianqijun.com/static/tianqi2018/ico2/b15.png"/></dd>
<dd class="temp">雪</dd>
<dd class="txt">0℃ ~ <b>2</b>℃</dd>
<dd class="txt">北风 3级</dd>
</dl>, <dl class="table_day7 ">
<dl>01月29日</dl>
<dd class="week">星期一</dd>
<dd class="air"><b style="background-color:#79b800;" title="空气质量:优">优</b></dd>
<dd class="img"><img src="http://pic9.tianqijun.com/static/tianqi2018/ico2/b1.png"/></dd>
<dd class="temp">多云</dd>
<dd class="txt">-2℃ ~ <b>3</b>℃</dd>
<dd class="txt">北风 3级</dd>
</dl>, <dl class="table_day7 ">
<dl>01月30日</dl>
<dd class="week">星期二</dd>
<dd class="air"><b style="background-color:#79b800;" title="空气质量:优">优</b></dd>
<dd class="img"><img src="http://pic9.tianqijun.com/static/tianqi2018/ico2/b0.png"/></dd>
<dd class="temp">晴</dd>
<dd class="txt">-2℃ ~ <b>4</b>℃</dd>
<dd class="txt">东北风 2级</dd>
</dl>, <dl class="table_day7 ">
<dl>01月31日</dl>
<dd class="week">星期三</dd>
<dd class="air"><b style="background-color:#79b800;" title="空气质量:优">优</b></dd>
<dd class="img"><img src="http://pic9.tianqijun.com/static/tianqi2018/ico2/b0.png"/></dd>
<dd class="temp">晴</dd>
<dd class="txt">-2℃ ~ <b>5</b>℃</dd>
<dd class="txt">北风 2级</dd>
</dl>, <dl class="table_day7 ">
<dl>02月01日</dl>
<dd class="week">星期四</dd>
<dd class="air"><b style="background-color:#79b800;" title="空气质量:优">优</b></dd>
<dd class="img"><img src="http://pic9.tianqijun.com/static/tianqi2018/ico2/b1.png"/></dd>
<dd class="temp">多云</dd>
<dd class="txt">-3℃ ~ <b>6</b>℃</dd>
<dd class="txt">东北风 1级</dd>
</dl>]

所有的数据现在已经全部拿到,现在就需要分解出各个小项中的内容,主要还是使用find方法来查找标签,而通过get_text()方法,我们就可以获取到具体的内容

def get_weather_report_list(weather_info):
weather_report_list = [] for group in weather_info:
detail_info = {}
txt = group.find_all(class_='txt')
# txt 中包含了温度范围及风向内容 detail_info['date'] = group.find('dl').get_text()
# dl 标签中对应的是日期 detail_info['description'] = group.find(class_='temp').get_text()
# temp 对应了天气状态 detail_info['temperature'] = txt[0].get_text()
detail_info['wind'] = txt[1].get_text() weather_report_list.append(detail_info) return weather_report_list

爬取的数据,我们只用了BeautifulSoup中 find()、find_all()及get_text() 这几个方法,就取得了我们想要的文本内容,非常的方便。

BeautifulSoup 库的使用记录的更多相关文章

  1. Python爬虫小白入门(三)BeautifulSoup库

    # 一.前言 *** 上一篇演示了如何使用requests模块向网站发送http请求,获取到网页的HTML数据.这篇来演示如何使用BeautifulSoup模块来从HTML文本中提取我们想要的数据. ...

  2. BeautifulSoup库children(),descendants()方法的使用

    BeautifulSoup库children(),descendants()方法的使用 示例网站:http://www.pythonscraping.com/pages/page3.html 网站内容 ...

  3. 网络爬虫BeautifulSoup库的使用

    使用BeautifulSoup库提取HTML页面信息 #!/usr/bin/python3 import requests from bs4 import BeautifulSoup url='htt ...

  4. BeautifulSoup库的使用

    1.简介 BeautifulSoup库也是一个HTML/XML的解析器,其使用起来很简单,但是其实解析网站用xpath和re已经足矣,这个库其实很少用到.因为其占用内存资源还是比xpath更高. '' ...

  5. python爬虫学习之使用BeautifulSoup库爬取开奖网站信息-模块化

    实例需求:运用python语言爬取http://kaijiang.zhcw.com/zhcw/html/ssq/list_1.html这个开奖网站所有的信息,并且保存为txt文件和excel文件. 实 ...

  6. python下载安装BeautifulSoup库

    python下载安装BeautifulSoup库 1.下载https://www.crummy.com/software/BeautifulSoup/bs4/download/4.5/ 2.解压到解压 ...

  7. 基于BeautifulSoup库的HTML内容的查找

    一.BeautifulSoup库提供了一个检索的参数: <>.find_all(name,attrs,recursive,string,**kwargs),它返回一个列表类型,存储查找的结 ...

  8. BeautifulSoup库

    '''灵活又方便的网页解析库,处理高效,支持多种解析器.利用它不用编写正则表达式即可方便的实现网页信息的提取.''' BeautifulSoup库包含的一些解析库: 解析库 使用方法 优势 劣势 py ...

  9. python BeautifulSoup库的基本使用

    Beautiful Soup 是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree). 它提供简单又常用的导航(navigating),搜索以 ...

随机推荐

  1. BZOJ 1594: [Usaco2008 Jan]猜数游戏 线段树 + 思维 + 二分

    Code: #include<bits/stdc++.h> #define maxn 3000000 using namespace std; void setIO(string s) { ...

  2. C#第七节课

    for嵌套 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System ...

  3. [Ynoi2011]D2T1

    题目大意: 给定一个数列$a$,有以下几种询问: 1. 给定$x$,在序列末尾插入$x$.2. 给定$l,r$,输出$\sum\limits_{i=l}^r a_i$.3. 给定$x$,将数列中的所有 ...

  4. [luogu2054 AHOI2005] 洗牌 (数论)

    传送门 Solution 我们考虑每一步牌的变化: 前半部分的牌位置*2 后半部分的牌位置*2-n-1 那么我们可以看做是\(x\times 2^m\equiv l \pmod n\) 于是求个逆元就 ...

  5. python的多版本安装以及常见错误(长期更新)

    (此文长期更新)Python安装常见错误汇总 注:本教程以python3.6为基准 既然是总结安装过程中遇到的错误,就顺便记录一下我的安装过程好了. 先来列举一下安装python3.6过程中可能需要的 ...

  6. CSS font-style中italic和Oblique有何区别 标签: css字体 2017-01-05 14:42 60人阅读 评论

    *要搞清楚这个问题,首先要明白字体是怎么回事.一种字体有粗体.斜体.下划线.删除线等诸多属性. 但是并不是所有字体都做了这些,一些不常用的字体,或许就只有个正常体,如果你用Italic,就没有效果了~ ...

  7. "AssertionError: View function mapping is overwriting an existing endpoint function"如何解决

    使用Flask定义URL的时候,如果出现"AssertionError: View function mapping is overwriting an existing endpoint ...

  8. keil uV4一个project内各个后缀名文件的作用

    1 test1 无后缀文件,这个是终于生成的文件.仅仅要有这个文件KEIL就能够软件仿真,不能打开 2 test1.hex 这个文件能够直接下载到单片机里,他就是从无后缀文件test1里提取的,去掉了 ...

  9. Swift学习——类的定义,使用,继承,构造等(五)

    Swift学习--类的定义,使用.继承,构造等(五) 类的使用说明 1 使用class和类名来创建一个类名,比如: class student 2 类中属性的声明和常量和变量一样,唯一的差别就是他们的 ...

  10. 开发,从需求出发 &#183; 之四 春天在这里

    首先,我要大字标语表达立场: 你所使用的framework & non-core features,就跟女人穿在身上的衣服一样,越少越好! watermark/2/text/aHR0cDovL ...