python - 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)
解决方案
您需要在函数中添加一个 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)
推荐阅读
- sql-server - 无法从存储过程或触发器读取/写入链接服务器(Ms Access)
- ios - 用于创建开发者或分发证书和推送证书的 CSR(证书签名请求)文件是否必须相同?
- c++ - 为什么输出是方框中的问号而不是数字?
- keycloak - Keycloak - 事件侦听器提供程序未触发新领域创建事件
- xamarin - 虽然在android中拒绝相机权限,但它不会再次询问
- unity3d - 穿过物体的光投射
- c++ - 为数组元素赋值后程序崩溃
- java - 我的图像没有被压缩 - 我该怎么办?
- docker - 我们可以从单个 docker 日志驱动程序将日志发送到多个位置吗
- android - Android Studio:使用 Firebase 显示当前用户数据的程序