python 学习笔记(二)——Beautifulsoup网络爬虫

python 网络爬虫学习第二天

学习 Beautifulsoup 库,进行网络爬虫,项目:中国天气网数据挖掘。

安装库

首先安装好需要的库 bs4

pip install bs4

要点记录

  • 网页解析 

 遇到的解析方式主要是 lxml 和 html5lib,网页不完整时,可用 html5lib 进行解析,防止出错。下面我就直接上代码

bs = BeautifulSoup(rep.content,'lxml',from_encoding='gbk')
  • 提取标签

利用 xx.find_all('Tag'),对标签进行提取,下面举一个栗子说明一下:大学生资源网,提取首页文本

1. 对 a 标签中的非标签文本进行提取,用 list() 返回列表 ,在这里需要说明一下 string、srtings、stripped_strings 的区别,在这里要感谢https://blog.csdn.net/github_36669230/article/details/66973617 这位大佬的帖子。用 string 属性来提取标签里的内容时,该标签应该是只有单个节点的,并且用 string 来提取文本时,不能有换行,有换行时会提取空对象;而用 strings 可直接提取所有文字;stripped_strings 可以去掉换行符和空格。

a_s = div.find_all('a',class_='list-group-item')
# 或者用 attrs{"class":'list-group-item'} 来进行属性限制
# a_s = div.find_all('a',attrs{"class":'list-group-item'})
text = list(a_s.stripped_strings)

2. 对 a 标签中的 href 属性进行提取,提取属性的两种方法在一下的代码中展示出来了。

for a in a_s:
    # 1.用下标
    href = a['href']
    # 2.用attrs
    href = a.attrs['href']
    print(href)

项目实战

中国天气网项目实战。

# encoding = "utf-8"
import requests
from bs4 import BeautifulSoup
from pyecharts import Bar
# 安装 pyecharts-snapshot:否则会报错 pip install pyecharts-snapshot

ALL_DATA = []
base_url = 'http://www.weather.com.cn/'
def pares_page(url):
    headers = {
        "User-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
    }
    response = requests.get(url,headers=headers)
    # html5lib 解析能力较强   lxml 解析速度快
    text = BeautifulSoup(response.content,'html5lib',from_encoding='utf-8')
    # print(text)
    ## 抓取第一页数据
    weather = text.find_all('div',class_='conMidtab')[0]    # 第一页天气状况
    # print(weather)
    tables = weather.find_all('table')
    # print(tables)
    for table in tables:
        trs = table.find_all('tr')[2:]
        for index,tr in enumerate(trs):
            tds = tr.find_all('td')
            # print(tds)
            # print('='*50)
            city_td = tds[0]
            if index == 0:          # 如果是第一个 tr 标签
                city_td = tds[1]    # 则取第二个 td 标签
            city = list(city_td.stripped_strings)[0]    # 提取td标签中的文字 不加[0] 时返回的是list数据,加[0]时返回的是str数据
            # print(type(city))
            temp_td = tds[-2]
            min_temp = list(temp_td.stripped_strings)[0]
            ALL_DATA.append({"city":city,"min_temp":int(min_temp)})     # int 讲字符串min_temp 变成整型
        # break

def main():
    base_url = 'http://www.weather.com.cn'
    for url in urls:
        # 查找地点跳转网址
         loacs = text.find_all('ul',class_='lq_contentboxTab2')
       # print(loacs)
         for li in loacs:
             list = li.find_all('a')
             for a in list:
                 href = a['href']
                 url = base_url+href
                 return url
        pares_page(url)
    ALL_DATA.sort(key=lambda data:data['min_temp'])     # 排序
    # print(ALL_DATA)
    data = ALL_DATA[0:10]
    print(data)
    cities = list(map(lambda x:x['city'],data))
    temps = list(map(lambda x:x['min_temp'],data))
    # 用 pyechart 作图
    chart = Bar('中国天气最低气温图')
    chart.add("",cities,temps)
    chart.render('cities_mintemp.html')


if __name__ == '__main__':
    main()

其中比较重要的一点是,enumerate 函数,提取相对无规律标签时可用下标来提取。

for index,tr in enumerate(trs):
            tds = tr.find_all('td')
            # print(tds)
            # print('='*50)
            city_td = tds[0]
            if index == 0:          # 如果是第一个 tr 标签
                city_td = tds[1]    # 则取第二个 td 标签
            city = list(city_td.stripped_strings)[0]    # 提取td标签中的文字 不加[0] 时返回的是list数据,加[0]时返回的是str数据

推荐阅读:

python 学习笔记(一)——Requests 库,网络爬虫

python 学习笔记(三)——读写csv文件

bs4官方文档中文版:BeautifulSoup

你可能感兴趣的:(python,html)