
python爬虫解析包含超链接的文本字段
在使用爬虫提取网页文本内容时,遇到带有超链接的文本字段导致无法完整提取的情况时,需要对xpath路径和内容处理方法进行适当的修改。
修改xpath路径
最初的xpath路径:
立即学习“Python免费学习笔记(深入)”;
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)










