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

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

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

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

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

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

原始代码:

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

import requestsfrom lxml import etreeimport htmlbase_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 += daprint(content_deal)

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

改进后的代码:

import requestsfrom lxml import etreebase_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爬虫如何提取网页中被超链接标签包裹的文本?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1359047.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 22:23:13
下一篇 2025年12月13日 22:23:26

相关推荐

发表回复

登录后才能评论
关注微信