我有以下具有多种情况的代码:
def _extract_property_value(selector: Selector) -> str:
raw_value = selector.xpath("span[2]")
default_value = raw_value.xpath("./text()").get().strip()
value_with_a = ', '.join([value.strip() for value in raw_value.xpath("./a /text()").getall()])
value_with_div_and_a = ', '.join([value.strip() for value in raw_value.xpath("./div /a /text()").getall()])
if value_with_a:
return value_with_a
elif value_with_div_and_a:
return value_with_div_and_a
elif default_value:
return default_value
Run Code Online (Sandbox Code Playgroud)
我想摆脱 if 语句并尽可能简化此代码。我不是优秀的 Pyton 开发者。我知道有模式“策略”,下面我试图实现它:
def _extract_property_value(selector: Selector) -> str:
raw_value = selector.xpath("span[2]")
values_dict = {
'default value': raw_value.xpath("./text()").get().strip(),
'value with a': ', '.join([value.strip() for value in raw_value.xpath("./a /text()").getall()]),
'value with div and a': ', '.join([value.strip() for …Run Code Online (Sandbox Code Playgroud)