Skip to main content
 首页 » 编程设计

python之不打印 xpath 的空结果

2024年12月31日9lori

我也需要从 xml 查询中获取空值,该查询将链接作为结果数组返回。有些度数没有链接可供引用。打印时,不会打印相应的空结果。

目的是获取相应度数的链接。

我的代码是:

  postgraduatedegrees=tree.xpath('//*[@id="block-scholarly-  
  content"]/div/article/div/div/div//*[contains(text(),"Degree  
  of")]/text()') 
 
  postgraduatedegreeslinks=tree.xpath('//*[@id="block-scholarly-  
  content"]/div/article/div/div/div//*[contains(text(),"Degree of")]/@href') 
 
  Output: 
   len(postgraduatedegrees) 
   Out[222]: 52 
 
  len(postgraduatedegreeslinks) 
   Out[223]: 40   

空值被移除。 请帮我解决问题

请您参考如下方法:

解决方案是

url="the url of the web page" 
page = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}) 
tree = html.fromstring(page.content) 
postgraduate=tree.xpath('//*[@id="block-scholarly-content"]/div/article/div/div/div//*[contains(text(),"Degree of")]') 
for pg in postgraduate: 
   pgcourse= pg.xpath('.//text()') 
   pglink=pg.xpath('.//@href') 

for 循环也会遍历空结果。