这是我用来抓取餐厅网站及其价格的代码。
def collect_dishes_list():
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
restaurants = {}
restaurant_sections = soup.find_all("div", class_="lunch--inner")
for section in restaurant_sections:
restaurant_name = section.find("h3").text.strip()
dishes = []
dish_items = section.find_all("div", class_="single-offer--content")
price_items = section.find_all("div", class_="single-offer--price")
for dish_item, price_item in zip(dish_items, price_items):
dish_name = dish_item.find("p").text.strip()
price = price_item.find("p").text.strip()
name = f'{dish_name} :{price}'
dishes.append(name)
restaurants[restaurant_name] = dishes
return restaurants
for restaurant, dishes in collect_dishes_list().items():
dict_to_send = {}
dict_to_send[restaurant] = dishes
yaml_string = yaml.dump(dict_to_send, allow_unicode=True)
utf8_yaml_string = yaml_string.encode("utf-8")
payload = {
"text": utf8_yaml_string.decode()
}
print(payload)
输出如下:
{'text': 'Restaurant_Name:\n- Dish_Name_1 :Price_1\n- Dish_Name_2 :Price_2\n'}
当我想在冒号后添加一个空格(如
name = f'{dish_name} : {price}'
)时,我的输出将用单引号括起来,例如
{'text': "Restaurant_Name:\n- 'Dish_Name_1 : Price_1'\n- 'Dish_Name_2 : Price_2'\n"}
为什么会发生这种情况?我想在冒号之前和之后有空格
尝试过使用任何其他字符串连接方式,似乎都无法解决问题:
dishes.append(f"{dish_name} : {price}")
price = " " + price_item.find("p").text.strip()
dishes.append(f"{dish_name} :{price}")
price = price_item.find("p").text.strip()
dishes.append(" : ".join([dish_name, price]))
引号可以保护原始字符串不被解释为单元素字典。您给
yaml.dump
一个 dict
将字符串映射到 list
的 str
,并且,如果没有引号,以空格分隔的字符串将看起来像 yaml
字典。为了防止这种情况(这样你会得到 list
的 str
,而不是单元素 list
的 dict
),yaml
添加引号。
删除空格就可以解决问题,因为
Dish_Name_1 :Price_1
不是 YAML 表示 dict
的方式(冒号后面需要有空格),所以它明确只是一个字符串,不需要引号。