安装:pip install bs4
,pip install lxml
文档:https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
from bs4 import BeautifulSoup
html
文档中的数据加载到该对象中fp = open('./test.html', 'r' , encoding='utf-8' )
soup = BeautifulSoup(fp, 'lxml' )
response = requests.get(url, data, headers=headers)
page_text = response.text
soup = BeatifulSoup(page_text, 'lxmL')
soup.tagName # 返回的是文档中第一次出现的`tagName`对应的标签
soup.find('tagName') # 等同于soup.tagName
soup.find_all('tagName') # 返回符合要求的所有标签(列表)
soup.find( 'div', class_/id/attr= '属性值')
select
选择器select('某种选择器(id, class, 标签...选择器) ') # 返回的是一个列表。
# 层级选择器
soup.select('.tang > ul > 1i > a') # >表示的是一个层级
soup. select('.tang > ul a') # 空格表示的多个层级
soup.a.text/string/get_text()
text/get_text() # 可以获取某一个标签中所有的文本内容
string # 只可以获取该标签下面直系的文本内容
soup.a['href']
import requests
from bs4 import BeautifulSoup
if __name__ == '__main__':
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
url = 'http://www.shicimingju.com/book/sanguoyanyi.html'
page_text = requests.get(url, headers=headers).text
soup = BeautifulSoup(page_text, 'lxml')
li_list = soup.select('.book-mulu > ul > li')
fp = open('./三国演义.txt', 'w', encoding='utf-8')
for li in li_list:
title = li.a.string
detail_url = 'http://www.shicimingju.com' + li.a['href']
detail_page_text = requests.get(detail_url, headers=headers).text
detail_soup = BeautifulSoup(detail_page_text, 'lxml')
div_tag = detail_soup.find('div', class_='chapter_content')
content = div_tag.text
fp.write(title + ':' + content + '\n')
print(title, '爬取成功!!')
print('数据爬取结束!!')
来源:爬虫开发入门丨老男孩IT教育