【问题标题】:Invalid Syntax with Try and Except [closed]Try 和 except 的无效语法[关闭]
【发布时间】:2021-03-03 05:33:22
【问题描述】:

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

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

您好,谁能帮忙,我不知道为什么会出现此错误,或者我在字典中漏掉了逗号或其他内容?

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

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)

【问题讨论】:

  • 您的字典定义中不能有try/except 块。我建议你把它放在一个函数中,然后改用它。
  • 嗨,我已经编辑了我的代码并包含了该函数,但现在我得到了最终的 excel 文件,其中只有链接但价格列是空的 :(
  • 现在您在 for 循环中声明函数。听起来不是个好主意。

标签: python function dictionary beautifulsoup try-catch


【解决方案1】:

你需要在函数中添加一个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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 2018-03-19
    • 2012-09-18
    • 1970-01-01
    • 2020-06-08
    相关资源
    最近更新 更多