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')
下次见!
相关文章推荐
- Python3.7 爬虫(二)使用 Urllib2 与 BeautifulSoup4 抓取解析网页
- python爬虫入门教程--HTML文本的解析库BeautifulSoup(四)
- python爬虫教程(6)-lxml解析网页
- 基于python利用爬虫爬取网页教程
- 在python使用selenium获取动态网页信息并用BeautifulSoup进行解析--动态网页爬虫
- 【教程】Python中第三方的用于解析HTML的库:BeautifulSoup
- Python爬虫beautifulsoup4常用的解析方法总结
- go语言解析网页利器goquery使用教程(爬虫必备)
- Python爬虫之使用BeautifulSoup解析HTML文本
- Python爬虫实战--(二)解析网页中的元素
- Python爬虫----网页解析器和BeautifulSoup第三方模块
- Python写爬虫——抓取网页并解析HTML
- python 网络爬虫与信息采取之解析网页(一)--BeautifulSoup库
- python网页解析器--BeautifulSoup
- python初级实战系列教程《二、爬虫之爬取网页小说》
- 【beautifulsoup】python标准库解析器解析网页问题解决
- Python写爬虫——抓取网页并解析HTML
- Python 网页解析之Beautifulsoup
- Python爬虫之解析网页
- Python3.x爬虫教程:爬网页、爬图片、自动登录