欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《如何使用Python爬虫完整提取包含超链接的文本内容?》,这篇文章主要讲到等等知识,如果你对文章相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

python爬虫解析包含超链接的文本字段
在使用爬虫提取网页文本内容时,遇到带有超链接的文本字段导致无法完整提取的情况时,需要对xpath路径和内容处理方法进行适当的修改。
修改xpath路径
最初的xpath路径:
content = html.xpath('//div[@class="f14 l24 news_content mt25zoom"]/p/text()')只能提取到<p>标签下的直接文本内容,而<a>标签内的文本会被忽略。要获取包含超链接的完整文本,需要将路径修改为:
content = html.xpath('//div[@class="f14 l24 news_content mt25 zoom"]/p//node()')此路径将获取所有<p>标签下节点(包括文本和标签),以便完整提取文本内容。
内容处理
获取到所有节点后,需要对内容进行处理,区分文本和超链接标签:
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"这样处理后,即使<p>标签嵌套了<a>标签,也能完整提取到文本和超链接的文本内容。
修改后的完整代码:
import requests
from 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爬虫完整提取包含超链接的文本内容?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!
本文内容来源于互联网,如有侵权请联系删除。
