百度百科网页爬取XPath返回空值:如何解决302重定向问题?(如何解决.重定向.百科.返回.网页...)

wufei1232025-03-08python5

百度百科网页爬取xpath返回空值:如何解决302重定向问题?

百度百科网页爬取XPath返回空值:302重定向及解决方案

在使用XPath爬取百度百科数据时,经常会遇到XPath表达式返回空值的情况。本文将深入分析导致此问题的一个常见原因——302重定向,并提供相应的Python代码解决方案。

问题描述:

以下代码尝试使用lxml库和XPath表达式提取百度百科词条摘要。然而,html.xpath()语句返回空列表,无法获取摘要信息。

import urllib.request
import urllib.parse
from lxml import etree

def query(content):
    url = 'https://baike.baidu.com/item/' + urllib.parse.quote(content)
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
    }
    req = urllib.request.Request(url=url, headers=headers, method='GET')
    response = urllib.request.urlopen(req)
    text = response.read().decode('utf-8')
    html = etree.HTML(text)
    sen_list = html.xpath('//div[contains(@class,"lemma-summary") or contains(@class,"lemmawgt-lemmasummary")]//text()')
    sen_list_after_filter = [item.strip('
') for item in sen_list]
    return ''.join(sen_list_after_filter)

if __name__ == '__main__':
    while True:
        content = input('查询词语:')
        result = query(content)
        print("查询结果:%s" % result)

问题分析:

使用curl命令测试百度百科请求,例如:curl https://baike.baidu.com/item/叶挺 -v,会发现请求被重定向(302 redirect)到一个新的URL,例如/item/%e5%8f%b6%e6%8c%ba/299649。 原始代码没有处理这个重定向,导致爬虫获取的是重定向前的页面,从而XPath表达式无法匹配到目标元素。

解决方案:

为了解决302重定向问题,需要在代码中添加重定向处理机制。 以下代码使用urllib.request.urlopen的特性自动处理重定向:

import urllib.request
import urllib.parse
from lxml import etree

def query(content):
    url = 'https://baike.baidu.com/item/' + urllib.parse.quote(content)
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
    }
    req = urllib.request.Request(url=url, headers=headers, method='GET')
    try:
        with urllib.request.urlopen(req) as response:  #自动处理重定向
            text = response.read().decode('utf-8')
            html = etree.HTML(text)
            sen_list = html.xpath('//div[contains(@class,"lemma-summary") or contains(@class,"lemmawgt-lemmasummary")]//text()')
            sen_list_after_filter = [item.strip('
') for item in sen_list]
            return ''.join(sen_list_after_filter)
    except urllib.error.URLError as e:
        return f"Error: {e.reason}"

if __name__ == '__main__':
    while True:
        content = input('查询词语:')
        result = query(content)
        print("查询结果:%s" % result)

改进后的代码使用with urllib.request.urlopen(req) as response:,urlopen函数会自动跟随重定向,获取最终的网页内容。 添加了try-except块来处理潜在的URL错误。 同时,更新了user-agent字符串,使其更贴近现代浏览器。 这将有效解决302重定向导致XPath返回空值的问题。

以上就是百度百科网页爬取XPath返回空值:如何解决302重定向问题?的详细内容,更多请关注知识资源分享宝库其它相关文章!

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。