Python爬虫:高效提取超链接文本
在使用Python爬虫抓取网页数据时,经常会遇到无法提取标签内文本的问题。本文将通过一个案例,演示如何改进代码,完美解决这个问题。
问题描述: 使用XPath表达式//div[@class="f14 l24 news_content mt25zoom"]/p/text()提取网页文本时,由于目标文本“绿色发展”嵌套在标签内,导致提取失败。原始代码仅获取了 标签下的纯文本,忽略了标签及其内容。 原始代码: 立即学习“Python免费学习笔记(深入)”; 解决方案: 关键在于改进XPath表达式和文本处理方式。原始XPath表达式仅提取文本节点,忽略了标签内的节点。 我们需要修改XPath表达式,并对提取到的节点进行类型判断。 改进后的代码: 通过修改XPath表达式为//div[@class="f14 l24 news_content mt25 zoom"]/p//node(),我们可以获取 标签下的所有节点,包括文本节点和标签。 代码中增加了节点类型判断,确保正确提取标签内的文本“绿色发展”,从而解决问题。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)
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)
以上就是Python爬虫如何提取网页中被超链接标签包裹的文本?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号