爬虫中beautifulsoup4解析页面

requeests - 请求页面,得到响应结果
beautifulsoup4 -根据响应结果解析页面、提取数据
写入文件、数据库
bs4安装时 要用beautifulsoup4

bs4模块能够从HTML或XML中提取数据

对网页进行解析,网页分为静态页面和动态页面

静态页面:内容是写死得,除非人为得进行内容修改,否则这个页面的内容是一层不变的。
动态页面:内容不是写死的,使用某种特殊的技术(JavaScript)使页面的数据通过某种方式显示在页面中

其中requests只能获得静态页面

如何分清页面时静态页面还是动态页面

网页中开发者工具:所给出得代码属于所有页面加载完成后得代码

查看页面源代码:所展示的是页面写入时的代码,即真代码。也是requests.get中我们中所展示得代码

如果为静态两者基本一致,动态的话两者差异很大。

BeautifulSoup(网页代码,解析器) —>将字符串类型得代码转换为bs4类型

bs模块提供了一些列提取数据的方法,这些方法的操作对象是bs4类型的数据

select:根据CSS选择(标签、class、id等)定位数据,得到的是符合这个选择器的所有结果(整体是列表,列表中每个元素是一个bs4类型的数据)
select_one:根据CSS选择(标签、class、id等)定位数据,得到的是符合这个选择器的一个结果(是一个bs4类型数据)
text:从bs4类型数据中提取标签内的内容,结果为字符串
attrs:从bs4类型数据中提取标签内属性值,结果为字符串
解析器有4种,此处用的是Python内置解析器’html.parser’

下面有个例子
import requests
from bs4 import BeautifulSoup

# bs4模块能够从html或xml中提取数据
for i in range(1, 11):
    URL = f'https://www.chinanews.com.cn/scroll-news/news{i}.html'

    # headers ={}   -->headers 是一个字典:{key:valus}
    # headers是给爬虫提供伪装的
    # User-Agent   -->将爬虫伪装成浏览器
    # 字典后面的值在开发者工具network中寻找
    Headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    }

    response = requests.get(url=URL, headers=Headers)
    # 状态码200,爬虫可用
    if response.status_code == 200:
        response.encoding = 'utf-8'
        # 打印网页源代码(字符串)
         print(response.text)
        # 对比打印结果得目的
        soup = BeautifulSoup(response.text, 'html.parser')
        # print(soup, type(soup))  # --->bs4类型的
        
        li_list = soup.select('body>div.w1280.mt20>div.content-left>div.content_list>ul>li')
        print(li_list)
        for i in li_list:
            if i.select_one('li>div.dd_lm>a') != None:
                news_tpye = i.select_one('li>div.dd_lm>a').text
                # print(news_tpye)
                news_title = i.select_one('li>div.dd_bt>a').text
                # print(news_title)
                news_href = 'https://www.chinanews.com.cn' + i.select_one('li>div.dd_bt>a').attrs['href']
                # print(news_href)
                news_time = i.select_one('li>div.dd_time').text
                # print(news_time)
                print(news_tpye, news_title, news_href, news_time)
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐