标签导航:

python爬虫如何提取网页中被超链接标签包裹的文本?

Python爬虫:高效提取超链接文本

在使用Python爬虫抓取网页数据时,经常会遇到无法提取标签内文本的问题。本文将通过一个案例,演示如何改进代码,完美解决这个问题。

问题描述: 使用XPath表达式//div[@class="f14 l24 news_content mt25zoom"]/p/text()提取网页文本时,由于目标文本“绿色发展”嵌套在标签内,导致提取失败。原始代码仅获取了

标签下的纯文本,忽略了标签及其内容。

原始代码:

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() + "
"
    content_deal += da
print(content_deal)

解决方案: 关键在于改进XPath表达式和文本处理方式。原始XPath表达式仅提取文本节点,忽略了标签内的节点。 我们需要修改XPath表达式,并对提取到的节点进行类型判断。

改进后的代码:

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)

通过修改XPath表达式为//div[@class="f14 l24 news_content mt25 zoom"]/p//node(),我们可以获取

标签下的所有节点,包括文本节点和标签。 代码中增加了节点类型判断,确保正确提取标签内的文本“绿色发展”,从而解决问题。