python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python BeautifulSoup网页

Python通过BeautifulSoup抓取网页数据并解析

作者:木觞清

这篇文章主要为大家介绍了如何使用Python的异步爬虫技术抓取网页内容,并使用BeautifulSoup解析特定div中的文本,感兴趣的小伙伴可以了解下

技术栈介绍

本教程使用了以下几个关键技术:

完整代码解析

import asyncio
from crawl4ai import AsyncWebCrawler
from bs4 import BeautifulSoup

async def extract_div_text(html_content):
    """
    从HTML内容中提取特定样式的div文本
    
    参数:
        html_content: 网页的HTML内容
        
    返回:
        提取到的文本内容或未找到的提示信息
    """
    soup = BeautifulSoup(html_content, 'html.parser')
    # 查找目标 div(根据 style 属性匹配)
    target_div = soup.find('div', style=lambda
        value: value and 'cursor: default;font-size: 16px;line-height: 1.8;padding: 0 19px 25px' in value)

    if target_div:
        # 获取 div 内的所有文本,并清理空白
        text = target_div.get_text(separator='\n', strip=True)
        return text
    return "目标 div 未找到"

async def main():
    """
    主函数,执行网页抓取和内容提取
    """
    async with AsyncWebCrawler() as crawler:
        # 抓取目标网页
        result = await crawler.arun("https://www.jjwxc.net/onebook.php?novelid=2490683&chapterid=2")
        
        if hasattr(result, 'html'):
            # 提取目标div中的文本
            extracted_text = await extract_div_text(result.html)
            print(extracted_text)  # 打印全部字符
        else:
            print("未能获取 HTML 内容")

if __name__ == "__main__":
    # 运行异步主函数
    asyncio.run(main())

代码分步讲解

1. 导入必要的库

import asyncio
from crawl4ai import AsyncWebCrawler
from bs4 import BeautifulSoup

2. 定义提取函数

async def extract_div_text(html_content):
    soup = BeautifulSoup(html_content, 'html.parser')
    target_div = soup.find('div', style=lambda
        value: value and 'cursor: default;font-size: 16px;line-height: 1.8;padding: 0 19px 25px' in value)
    # ...其余代码...

这个函数负责:

3. 主函数

async def main():
    async with AsyncWebCrawler() as crawler:
        result = await crawler.arun("目标URL")
        # ...处理结果...

主函数使用异步上下文管理器创建爬虫实例,并抓取目标网页。

技术要点

异步编程:使用async/await语法提高爬虫效率

精确选择器:通过style属性的部分匹配定位目标元素

文本清理:使用get_text()方法提取干净文本

应用场景

这种技术可用于:

注意事项

遵守目标网站的robots.txt规则

设置适当的请求间隔避免被封禁

处理可能的异常情况(网络错误、元素不存在等)

总结

本文展示了如何使用Python异步爬虫高效抓取网页并提取特定内容。异步编程可以显著提高爬虫效率,而BeautifulSoup提供了灵活的HTML解析能力。你可以根据需要修改选择器逻辑来适应不同的网页结构。

到此这篇关于Python通过BeautifulSoup抓取网页数据并解析的文章就介绍到这了,更多相关Python BeautifulSoup网页内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文