您的位置:首页 > 编程语言 > Python开发

python爬虫教程(5)-BeautifulSoup解析网页

2019-02-16 18:16 323 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_42183408/article/details/87459848

欢迎来到python爬虫大讲堂,现在开始你的爬虫旅程吧!

使用BeautifulSoup解析

BeautifulSoup提供了从HTML中提取数据的功能,相对正则表达式来说,BeautifulSoup较为简单,所以放松!

安装

pip install bs4

使用BeautifulSoup获取日期

我们在上一篇文章中使用了正则表达式获取博客发布日期,这次我们使用BeautifulSoup来获取时间,首先获取一个:

import requests
from bs4 import BeautifulSoup
link='https://blog.csdn.net/weixin_42183408'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
r=requests.get(link,headers=headers,timeout=20)

soup=BeautifulSoup(r.text,'lxml')
date=soup.find('span',class_='date').text.strip()

print('the date is',date)

这样你会得到类似于这样的结果:

the date is 2019-02-16 17:26:44

首先我们用lxml解析网页,

BeautifulSoup(r.text,'lxml')
,接下来我们来用soup.find来找到第一个日期:
soup.find('span',class_='date').text.strip()
,HTML源码是这样的:

<span class="date">2019-02-15 17:20:11</span>

因此我们发现是span标签,有一个class属性为date,因此我们可以用

'span',class_=;date'
,注意class后要加_,因此是
class_

接下来我们使用find_all来找到所有博客日期并加入翻页功能:

import requests
from bs4 import BeautifulSoup

headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
for i in range(1,4):
link='https://blog.csdn.net/weixin_42183408/article/list/'+str(i)+'?'
r=requests.get(link,headers=headers,timeout=20)

soup=BeautifulSoup(r.text,'lxml')
date=soup.find_all('span',class_='date')
for x in date:
date=x.text.strip()
print('the date is',date)

这里我们使用for循环翻页,并使用find_all找到所有的。

注意:这里soup.find_all之后不能直接用text.strip(),因为find_all返回一个列表

恭喜你已经掌握了BeautifulSoup的基本功能!

BeautifulSoup的其它功能

BeautifulSoup的HTML代码美化功能:

soup=BeautifulSoup(r.text,'lxml)
print(soup.prettify())

遍历文档树

遍历文档树并获取span标签:

soup.header.span

div标签的所有子节点,返回列表:

soup.header.div.contents

children方法获取所有子标签:

soup.header.div.children

所有子子孙孙节点:

soup.header.div,descontents

获取父节点:

soup.header.div.a.parent

遍历文档树我们一般不常用,所以我们介绍一下搜索文档树:

搜索文档树

获取所有h开头的标签,结合正则表达式,匹配字符串开头的^:

list=soup.find_all(re.compile(^h))
for tag_name in list:
print(tag_name)

## select

通过标签查找:

soup.select(div a)
soup.select('div>a')

下次见!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: