Python爬虫如何提取网页中被超链接标签包裹的文本?

碧海醫心
发布: 2025-03-11 11:48:23
原创
891人浏览过

python爬虫如何提取网页中被超链接标签包裹的文本?

Python爬虫:高效提取超链接文本

在使用Python爬虫抓取网页数据时,经常会遇到无法提取标签内文本的问题。本文将通过一个案例,演示如何改进代码,完美解决这个问题。

问题描述: 使用XPath表达式//div[@class="f14 l24 news_content mt25zoom"]/p/text()提取网页文本时,由于目标文本“绿色发展”嵌套在标签内,导致提取失败。原始代码仅获取了

标签下的纯文本,忽略了标签及其内容。

原始代码:

立即学习Python免费学习笔记(深入)”;

import requests
from lxml import etree
import html

base_url = "https://www.solidwaste.com.cn/news/342864.html"
resp = requests.get(url=base_url)
html = etree.html(resp.text)

encod = html.xpath('//meta[1]/@content')
if encod:
    encod = encod[0].split("=")[-1]
    resp.encoding = encod
    html = etree.html(resp.text)

content = html.xpath('//div[@class="f14 l24 news_content mt25zoom"]/p/text()')
print(content)

content_deal = ""
for i in content:
    da = i.strip() + "\n"
    content_deal += da
print(content_deal)
登录后复制

解决方案: 关键在于改进XPath表达式和文本处理方式。原始XPath表达式仅提取文本节点,忽略了标签内的节点。 我们需要修改XPath表达式,并对提取到的节点进行类型判断。

改进后的代码:

import requests
from lxml import etree

base_url = "https://www.solidwaste.com.cn/news/342864.html"
resp = requests.get(url=base_url)
html = etree.HTML(resp.text)

encod = html.xpath('//meta[1]/@content')
if encod:
    encod = encod[0].split("=")[-1]
    resp.encoding = encod
    html = etree.HTML(resp.text)

content = html.xpath('//div[@class="f14 l24 news_content mt25 zoom"]/p//node()')

content_deal = ""
for node in content:
    if isinstance(node, etree._ElementUnicodeResult):
        content_deal += node.strip() + "\n"
    elif isinstance(node, etree._Element) and node.tag == 'a':
        content_deal += node.text.strip() + "\n"

print(content_deal)
登录后复制

通过修改XPath表达式为//div[@class="f14 l24 news_content mt25 zoom"]/p//node(),我们可以获取

标签下的所有节点,包括文本节点和标签。 代码中增加了节点类型判断,确保正确提取标签内的文本“绿色发展”,从而解决问题。

以上就是Python爬虫如何提取网页中被超链接标签包裹的文本?的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号