使用BeautifulSoup解析网页元素

说明

主要两步,1.使用requests请求内容 2.使用beautifulsoup将内容转换为可操作的DOM结构

我们使用requests获取网页内容,但都是带有标签的内容,很难直接使用
使用BeautifulSoup4套件 可以操作DOM树
首先要引入BeautifulSoup4
from bs4 import BeautifulSoup
使用时通常要制定解析器soup = BeautifulSoup(res.text,'html.parser')一般为html.parser

soup元素的text是获取文本内容。
soup元素的contents有所不同,会分开获取。

选择soup元素soup.select() 可以使用选择符 标签是标签名 id是# 类是. 属性是字典通过中括号获取

查找元素时通常借助Google开发工具的观察工具或者使用infoLite工具 查找要找到元素 在Google商店里已经更名为SelectorGadget 搜索原来的infolite已经搜不到了。

实例1 -获取新浪的最新新闻的标题时间和链接

import requests
from bs4 import BeautifulSoup

res = requests.get('http://news.sina.com.cn/china/')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text,'html.parser')
for news in soup.select('.news-item'):
    if len(news.select('h2')) > 0:
        time = news.select('.time')[0].text
        h2 = news.select('h2')[0].text
        a = news.select('a')[0]['href']
        print(time,h2,a)

实例2 -获取单个文章的标题,文章内容,时间,责任编辑,评论数

#获取内容,转为soup
import requests
from bs4 import BeautifulSoup
res = requests.get('http://news.sina.com.cn/c/nd/2017-07-18/doc-ifyiamif3452348.shtml')
res.encoding='utf-8'
soup = BeautifulSoup(res.text,'html.parser')
#选择标题
soup.select('#artibodyTitle')[0].text
#选择时间
timesource = soup.select('.time-source')[0].contents[0].strip()
from datetime import datetime
dt = datetime.strptime(timesource,'%Y年%m月%d日%H:%M')
dt.strftime('%Y-%m-%d')
source = soup.select('.time-source span a')[0].text
#选择文章内容
article = []
for p in soup.select('#artibody p')[:-1]:
    article.append(p.text.strip())
# print(article)
' '.join(article)
#或者一行搞定
 ' '.join([p.text.strip() for p in soup.select('#artibody p')[:-1]])
#选择责任编辑
soup.select('.article-editor')[0].text.lstrip('责任编辑:')
# 获取评论数
#是在js中的,要请求js,并删除多余的部分,然后将js代码转换为json格式字典
comments = requests.get('http://comment5.news.sina.com.cn/page/info?version=1&format=js&channel=gn&newsid=comos-fyiamif3452348&group=&compress=0&ie=utf-8&oe=utf-8&page=1&page_size=20&jsvar=loader_1500398040328_33412017')
import json
jd = json.loads(comments.text.lstrip('var loader_1500398040328_33412017='))
jd['result']['count']['total']
#获取新闻编号
newsurl = 'http://news.sina.com.cn/c/nd/2017-07-18/doc-ifyiamif3452348.shtml'
newsurl.split('/')[-1].lstrip('doc-i').rstrip('.shtml')
#或者使用正则表达式
import re
m = re.search('doc-i(.+).shtml',newsurl)
m.group(1)

以上还涉及到了字符串修剪,时间格式转化,json格式转换,正则表达式等,需注意。

你可能感兴趣的:(使用BeautifulSoup解析网页元素)