爬虫系列二(数据清洗--->bs4解析数据)

一 BeautifulSoup解析

1 环境安装

- 需要将pip源设置为国内源,阿里源、豆瓣源、网易源等
   - windows
    (1)打开文件资源管理器(文件夹地址栏中)
    (2)地址栏上面输入 %appdata%3)在这里面新建一个文件夹  pip
    (4)在pip文件夹里面新建一个文件叫做  pip.ini ,内容写如下即可
        [global]
        timeout = 6000
        index-url = https://mirrors.aliyun.com/pypi/simple/
        trusted-host = mirrors.aliyun.com
   - linux
    (1)cd ~2)mkdir ~/.pip
    (3)vi ~/.pip/pip.conf
    (4)编辑内容,和windows一模一样
- 需要安装:pip install bs4
     bs4在使用时候需要一个第三方库,把这个库也安装一下
     pip install lxml

2 基础解析

使用流程:       
    - 导包:from bs4 import BeautifulSoup
    - 使用方式:可以将一个html文档,转化为BeautifulSoup对象,然后通过对象的方法或者属性去查找指定的节点内容
        (1)转化本地文件:
             - soup = BeautifulSoup(open('本地文件'), 'lxml')
        (2)转化网络文件:
             - soup = BeautifulSoup('字符串类型或者字节类型', 'lxml')
        (3)打印soup对象显示内容为html文件中的内容

基础巩固:
    (1)根据标签名查找
        - soup.a   只能找到第一个符合要求的标签
    (2)获取属性
        - soup.a.attrs  获取a所有的属性和属性值,返回一个字典
        - soup.a.attrs['href']   获取href属性
        - soup.a['href']   也可简写为这种形式
    (3)获取内容
        - soup.a.string
        - soup.a.text
        - soup.a.get_text()
       【注意】如果标签还有标签,那么string获取到的结果为None,而其它两个,可以获取文本内容
    (4)find:找到第一个符合要求的标签
        - soup.find('a')  找到第一个符合要求的
        - soup.find('a', title="xxx")
        - soup.find('a', alt="xxx")
        - soup.find('a', class_="xxx")
        - soup.find('a', id="xxx")
    (5)find_all:找到所有符合要求的标签
        - soup.find_all('a')
        - soup.find_all(['a','b']) 找到所有的a和b标签
        - soup.find_all('a', limit=2)  限制前两个
    (6)根据选择器选择指定的内容
               select:soup.select('#feng')
        - 常见的选择器:标签选择器(a)、类选择器(.)、id选择器(#)、层级选择器
            - 层级选择器:(使用比较多)
                div .dudu #lala .meme .xixi  下面好多级
                div > p > a > .lala          只能是下面一级
【注意】select选择器返回永远是列表,需要通过下标提取指定的对象

爬取三国演义书籍

# 下载三国演义书籍http://www.shicimingju.com/book/sanguoyanyi.html
import requests
from bs4 import BeautifulSoup

'''
    解析流程:
        1.pip install bs4
        2.导包:from bs4 import BeautifulSoup
        3.实例化一个BeautifulSoup对象(将页面源码数据加载到该对象中)
        4.调用BeautifulSoup对象中的相关属性和方法进行标签的定位
'''

url='http://www.shicimingju.com/book/sanguoyanyi.html'

headers={
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.20 Safari/537.36'
}

page_data=requests.get(url=url,headers=headers).text

#实例化一个BeautifulSoup对象
soup=BeautifulSoup(page_data,'lxml')
li_list=soup.select('."book-mulu" > ul > li')

fp=open('三国演义.txt','w',encoding='utf8')

for li in li_list:
    url='http://www.shicimingju.com'+li.a['href']
    section_page_data=requests.get(url=url,headers=headers).text

    soup=BeautifulSoup(section_page_data,'lxml')
    section_title=soup.select('.www-main-container > h1')[0].string
    section_content=soup.find('div',class_="chapter_content").text
    fp.write(section_title+'
'+section_content+'

')
    print(section_title+'	'+'下载完成')
fp.close()
原文地址:https://www.cnblogs.com/angle6-liu/p/10438103.html