Python爬虫如何完整提取包含在超链接中的网页文本?

python爬虫如何完整提取包含在超链接中的网页文本?

Python爬虫:完整提取超链接中的网页文本

在使用Python爬虫抓取网页信息时,经常遇到文本嵌套在标签中的情况。直接使用text()方法会忽略标签内的内容,导致信息丢失。本文提供一种解决方案,确保完整提取所有文本信息。

问题:

爬取新闻网站时,部分文本位于标签内,导致XPath表达式//div[@class=”f14 l24 news_content mt25zoom”]/p/text()无法完整提取文本。“绿色发展”等词语因嵌套在标签中而被遗漏。

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

原始代码使用//div[@class=”f14 l24 news_content mt25zoom”]/p/text()仅提取文本节点,忽略标签及其内容。

解决方案:

修改XPath表达式并进行节点类型判断,分别处理文本节点和标签节点。

首先,将XPath表达式修改为//div[@class=”f14 l24 news_content mt25 zoom”]/p//node()。//node()提取所有子节点,包括文本节点和标签。

然后,遍历所有节点,判断节点类型。如果是文本节点,直接提取文本;如果是标签节点,提取标签的文本内容。

改进后的代码如下:

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)

登录后复制

本文来自互联网或AI生成,不代表软件指南立场。本站不负任何法律责任。

如若转载请注明出处:http://www.down96.com/tutorials/2257.html

热心网友热心网友
上一篇 2025-04-11 14:23
下一篇 2025-04-11 14:23

相关推荐

本站[软件指南]所有内容来自互联网投稿或AI智能生成,并不代表软件指南的立场。