首页 > 解决方案 > Try 和 except 的语法无效

问题描述

所以我正在尝试抓取一个鞋类网站.. 两个价格显示原价和以前的价格。

我试图只得到原件,因此尝试和除外

嗨,谁能帮忙,我不知道为什么我会收到这个错误,或者我在字典中错过了逗号或其他内容?

我的缩进是正确的。可能是什么问题呢 ??:(

from requests_html import HTMLSession
from bs4 import BeautifulSoup
import pandas as pd
       
s = HTMLSession()
        ​    
r = s.get("https://www.koovs.com/men/footwear/?type=list&sort=price-low&filter_style_fq=18030")
    
r.html.render(sleep=3)        ​
        ​        ​    
soup = BeautifulSoup(r.text,"lxml")
        
All = soup.find_all('li',class_='imageView')
        ​    
Prods = []
        ​   
for a in All:

  def Price(a):

   try:

    a.find("span", class_= "product_price").next.text

   except:

    a.find("span", class_= "product_price").text

  F = {"Links" : f'https://www.koovs.com{a.find("a")["href"]}',
  "Price" : Price(a)}

  Prods.append(F)
    
Final = pd.DataFrame(Prods)
    
Final.to_excel("Links.xlsx",index = False)

标签: pythonfunctiondictionarybeautifulsouptry-catch

解决方案


您需要在函数中添加一个 return 语句,否则它只会返回 None。

return a.find("span", class_= "product_price").next.text

另外我会在循环之外声明你的函数。

from requests_html import HTMLSession
from bs4 import BeautifulSoup
import pandas as pd

def Price(a):

   try:
        return a.find("span", class_= "product_price").next.text
   except:
        return a.find("span", class_= "product_price").text

s = HTMLSession()
r = s.get("https://www.koovs.com/men/footwear/?type=list&sort=price-low&filter_style_fq=18030")
r.html.render(sleep=3)
soup = BeautifulSoup(r.text,"lxml")    
All = soup.find_all('li',class_='imageView')

Prods = []
for a in All:
    F = {"Links" : f'https://www.koovs.com{a.find("a")["href"]}',
         "Price" : Price(a)}
    Prods.append(F)
    
Final = pd.DataFrame(Prods)
    
Final.to_excel("Links.xlsx",index = False)

推荐阅读