Python Try和Except的语法无效
所以我想在一个鞋类网站上浏览。。两个价格显示了原价和原价 我试图只得到原件,因此尝试和例外 嗨,有人能帮忙吗,我不知道为什么我会出现这个错误,或者我的字典里漏掉了一个逗号或什么 我的缩进是正确的。可能是什么问题??:(Python Try和Except的语法无效,python,function,dictionary,beautifulsoup,try-catch,Python,Function,Dictionary,Beautifulsoup,Try Catch,所以我想在一个鞋类网站上浏览。。两个价格显示了原价和原价 我试图只得到原件,因此尝试和例外 嗨,有人能帮忙吗,我不知道为什么我会出现这个错误,或者我的字典里漏掉了一个逗号或什么 我的缩进是正确的。可能是什么问题??:( 来自请求\u html导入HTMLSession 从bs4导入BeautifulSoup 作为pd进口熊猫 s=HTMLSession() r=s.get(“https://www.koovs.com/men/footwear/?type=list&sort=pric
来自请求\u html导入HTMLSession
从bs4导入BeautifulSoup
作为pd进口熊猫
s=HTMLSession()
r=s.get(“https://www.koovs.com/men/footwear/?type=list&sort=price-低和过滤器(样式(fq=18030”)
r、 render(sleep=3)
汤=美汤(右文本,“lxml”)
All=soup.find_All('li',class='imageView')
产品=[]
总的来说:
def价格(a):
尝试:
a、 查找(“span”,class=“product\u price”)。next.text
除:
a、 查找(“span”,class=“产品价格”)。文本
F={“链接”:F'https://www.koovs.com{a.find(“a”)[“href”]},
“价格”:价格(a)}
产品附加(F)
最终=pd.数据帧(产品)
Final.to_excel(“Links.xlsx”,index=False)
您需要向函数中添加一个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)
您的字典定义中不能有
try/except
块。我建议您将它放在函数中,然后使用它。您好,我已经编辑了代码并包含了函数,但现在我得到了最终的excel文件,其中只有链接,但价格列为空:(现在在for循环中声明函数。听起来不是个好主意。