标签导航:

python爬虫如何完整提取包含在超链接中的网页文本?

Python爬虫:完整提取超链接中的网页文本

在使用Python爬虫抓取网页信息时,经常遇到文本嵌套在标签中的情况。直接使用text()方法会忽略标签内的内容,导致信息丢失。本文提供一种解决方案,确保完整提取所有文本信息。

问题:

爬取新闻网站时,部分文本位于标签内,导致XPath表达式//div[@class="f14 l24 news_content mt25zoom"]/p/text()无法完整提取文本。“绿色发展”等词语因嵌套在标签中而被遗漏。

原始代码使用//div[@class="f14 l24 news_content mt25zoom"]/p/text()仅提取文本节点,忽略标签及其内容。

解决方案:

修改XPath表达式并进行节点类型判断,分别处理文本节点和标签节点。

首先,将XPath表达式修改为//div[@class="f14 l24 news_content mt25 zoom"]/p//node()。//node()提取所有子节点,包括文本节点和标签。

然后,遍历所有节点,判断节点类型。如果是文本节点,直接提取文本;如果是标签节点,提取标签的文本内容。

改进后的代码如下:

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() + "
"
    elif isinstance(node, etree._Element) and node.tag == 'a':
        content_deal += node.text.strip() + "
"

print(content_deal)

通过以上改进,代码能够完整提取标签内的文本内容,避免信息丢失。 代码中对编码处理进行了优化,避免了因=号重复出现导致的错误。