解决百度百科XPath爬取空值的302重定向难题
时间:2025-04-02
浏览:203
作者:佚名
本文针对使用XPath爬取百度百科数据时遇到的空值问题,深入分析了302重定向的根本原因。由于百度百科URL存在重定向,原始代码未处理此情况,导致XPath无法匹配目标元素,返回空值。文章提供了基于Python和lxml库的解决方案,通过改进代码,利用`urllib.request.urlopen`自动处理302重定向,并添加错误处理机制,最终成功获取百度百科词条摘要信息,有效解决了XPath爬取空值难题。 关键词:百度百科,XPath,爬虫,302重定向,Python,lxml

百度百科网页爬取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('\n') 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('\n') 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重定向难题》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
