Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库。
Tag就是html中的一个标签,用BeautifulSoup就能解析出来Tag的具体内容,具体的格式为 soup.name,其中name是html下的标签名。
先找一段html文本作为测试数据:
html = """
The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
westos,
Lacie and
Tillie;
and they lived at the bottom of a well.
...
"""
然后导入BeautifulSoup模块,并实例化一个soup对象:
from bs4 import BeautifulSoup
# 'html.parser':Python标准库解析器
soup = BeautifulSoup(html,'html.parser')
# lxml解析器
# soup = BeautifulSoup(html,'lxml')
上面两个解析器都可以,推荐使用lxml,但是lxml需要安装第三方库。
标签的常用属性:name、attrs
soup.标签名 查找的是在所有内容中的第一个符合要求的标签,如果标签名只有一个,可以根据 soup.标签名 获取到标签。
print(soup.title)
print(soup.title.name) # 获取标签的名称
print(soup.title.string) # 获取标签里面的内容
print(soup.a.attrs)
print(soup.a.attrs['href'])
标签常用方法
get方法:
用于得到标签下的属性值,注意这是一个重要的方法,在许多场合都能用到,比如你要得到 < img src="#"> 标签下的图像url,那么就可以用soup.img.get(‘src’)
# 如果由多个a标签,则可以获取到第一个a标签的内容
print(soup.a.get('href'))
print(soup.a.get('class'))
string方法:
得到标签下的文本内容,只有在此标签下没有子标签,或者只有一个子标签的情况下才能返回其中的内容,否则返回的是None
print(soup.a.string) # 获取标签里面的内容
get_text()方法:
可以获得一个标签中的所有文本内容,包括子孙节点的内容,这是最常用的方法
print(soup.a.get_text())
对获取的属性信息进行修改
print(soup.a.get('href'))
soup.a['href'] = 'http://www.baidu.com'
print(soup.a.get('href'))
print(soup.a)
# 查找符合条件的所有标签
aTagObj = soup.find_all('a')
print(aTagObj)
for item in aTagObj:
print(item)
# 需求:获取所有类名为'sister'的a标签
print(soup.find_all('a',class_='sister'))
# 需求:获取第一个p标签或a标签
print(soup.find(['p','a']))
# 需求:获取所有p标签或a标签
print(soup.find_all(['p','a']))
# 需求:获取所有符合条件p标签或a标签
print(soup.find_all(['p','a'],class_=['title','sister1']))
import re
print(soup.find_all(text="The Dormouse's story"))
print(soup.find_all(text=re.compile('.*story')))
标签选择器
print(soup.select('title'))
类选择器(.类名)
print(soup.select('.sister1'))
id选择器(#id名称)
print(soup.select('#link1'))
属性选择器
print(soup.select("input[type='password']"))
import requests
from bs4 import BeautifulSoup
def get_content(url):
try:
user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0'
response = requests.get(url,headers={'User-Agent':user_agent})
response.raise_for_status() # 如果返回的状态码不是200,则抛出异常
response.encoding = response.apparent_encoding # 根据响应信息判断网页的编码格式,便于response.text知道如何解码
except Exception as e:
print('爬取错误')
else:
print('爬取成功')
return response.text
def parser_content(htmlContent):
# 实例化soup对象
soup = BeautifulSoup(htmlContent,'html.parser')
# 提取页面的头部信息,解决乱码问题
headObj = soup.head
# 提取需要的内容
divObj = soup.find_all('div',class_='blog-content-box')
with open('doc/csdn.html','w') as f:
f.write(str(headObj))
f.write(str(divObj))
print('下载成功......')
if __name__ == '__main__':
url = 'https://blog.csdn.net/King15229085063/article/details/87382834'
content = get_content(url)
parser_content(content)