
Python爬虫:完整提取超链接中的网页文本
在使用Python爬虫抓取网页信息时,经常遇到文本嵌套在<a></a>标签中的情况。直接使用text()方法会忽略<a></a>标签内的内容,导致信息丢失。本文提供一种解决方案,确保完整提取所有文本信息。
问题:
爬取新闻网站时,部分文本位于<a></a>标签内,导致XPath表达式//div[@class="f14 l24 news_content mt25zoom"]/p/text()无法完整提取文本。“绿色发展”等词语因嵌套在<a></a>标签中而被遗漏。
立即学习“Python免费学习笔记(深入)”;
原始代码使用//div[@class="f14 l24 news_content mt25zoom"]/p/text()仅提取文本节点,忽略<a></a>标签及其内容。
解决方案:
修改XPath表达式并进行节点类型判断,分别处理文本节点和<a></a>标签节点。
首先,将XPath表达式修改为//div[@class="f14 l24 news_content mt25 zoom"]/p//node()。//node()提取所有子节点,包括文本节点和<a></a>标签。
然后,遍历所有节点,判断节点类型。如果是文本节点,直接提取文本;如果是<a></a>标签节点,提取<a></a>标签的文本内容。
改进后的代码如下:
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)通过以上改进,代码能够完整提取<a></a>标签内的文本内容,避免信息丢失。 代码中对编码处理进行了优化,避免了因=号重复出现导致的错误。
以上就是Python爬虫如何完整提取包含在超链接中的网页文本?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号