Python爬虫——BeautifulSoup的基本使用
pip install beautifulsoup4
1.创建BeautifulSoup对象
import bs4
import requests
url = "http://www.baidu.com"
htmlFile = requests.get(url)
htmlFile.encoding = htmlFile.apparent_encoding
objSoup = bs4.BeautifulSoup(htmlFile.text, 'lxml')
print(type(objSoup))
1.2内容解析
- BeautifulSoup对象.标签名:返回标签首次出现的内容
title = objSoup.title
print(title)
print(objSoup.title.text)
- find()函数:返回HTML文件中第一次出现的标签内容。也可以用于查找某个有特定属性的标签。
first_a = objSoup.find('a')
print(first_a)
findById = objSoup.find('a', class_='mnav')
print(findById)
find_attrs = objSoup.find(attrs={'class': 'mnav'})
print(find_attrs)
- find_all():查找HTML中所有符合的标签内容,返回列表。
list_a = objSoup.find_all('a')
print(list_a)
for a in list_a:
print(a.text)
for i in range(len(list_a)):
print(list_a[i].getText)
list2 = objSoup.find_all(['div', 'a'])
print(list2)
print(len(list2))
import re
list3 = objSoup.find_all(re.compile('^a'))
print(list3)
list4 = objSoup.find_all(re.compile('^li'))
print(list4)
- select()
select()主要是以CSS选择器(selector)的方式寻找元素。如果找到元素,则返回元素列表;否则返回空列表。
- 标签选择器:直接指定标签名
- objSoup.select(‘p’):寻找所有<p>标签的元素;
- objSoup.select(‘img’):寻找所有<img>标签的元素
- objSoup.select(‘input[name]’):寻找所有<input>标签且包含name属性的元素;
- 类(class)选择器:.
- objSoup.select('.name):寻找所有class属性为name的元素;
- id选择器:#
- objSoup.select('#name):寻找所有id属性为name的元素;
- 层级选择器:
- 单层:>
- objSoup.select(‘div.list > ul > li > a’):查找所有class为list的div中的ul里的li标签里面的a标签;
- 多层:空格
- objSoup.select(‘p #name’):寻找所有<p>标签且id为name的元素
- objSoup.select(‘p .name’):寻找所有class为name的<p>标签;
list5 = objSoup.select('p')
print(list5)
list6 = objSoup.select('.mnav')
print(list6)
list7 = objSoup.select('#lh')
print(list7)
list8 = objSoup.select('#lh a')
print(list8)
- 获取标签文本内容
- text:获取标签下的全部文本内容
- get_text():获取标签下的全部文本内容
- string:只能获取到标签下的直系文本内容
- get()获取标签属性:如:a.get(‘href’)
- 获取标签属性值
- 通过选择器获取,如:
- objSoup.select(‘#lh a’)[0].get(‘href’)
- objSoup.select(‘#lh a’)[0][‘href’]
- find()函数获取:
- objSoup.find(‘a’)[‘href’]
- 通过find_all方法获取:
- objSoup.find_all(‘a’)[2][‘href’]
text = objSoup.select('#lh a')[0].text
print(text)
str1 = objSoup.select('#lh a')[0].string
print(str1)
text2 = objSoup.select('#lh a')[0].get_text()
print(text2)
href = objSoup.select('#lh a')[0].get('href')
print(href)
first_a = objSoup.find('a')['href']
print(first_a)
list_a = objSoup.find_all('a')[2]
print(list_a['href'])
参考: