如何使用Python爬虫完整提取包含超链接的文本内容?

如何使用python爬虫完整提取包含超链接的文本内容?

python爬虫解析包含超链接的文本字段

在使用爬虫提取网页文本内容时,遇到带有超链接的文本字段导致无法完整提取的情况时,需要对xpath路径和内容处理方法进行适当的修改。

修改xpath路径

最初的xpath路径:

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

content = html.xpath('//div[@class="f14 l24 news_content mt25zoom"]/p/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"

这样处理后,即使

标签嵌套了标签,也能完整提取到文本和超链接的文本内容。

修改后的完整代码:

import requestsfrom lxml import etree# 爬取并转化为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 mt25 zoom"]//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爬虫完整提取包含超链接的文本内容?的详细内容,更多请关注创想鸟其它相关文章!

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

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 17:30:46
下一篇 2025年12月13日 17:30:54

相关推荐

发表回复

登录后才能评论
关注微信