with open('./第{}页.txt'.format(i), 'w', encoding='utf-8') as fp: for num in dish_urls: new_url = f'https://www.haochu.com{num}' # 把菜品具体网址作为新url,获取每道菜所需的食材 print(new_url) response2 = requests.get(url=new_url, headers=headers) html_data2 = etree.HTML(response2.text) # 新网址的html——data2 ints_names = html_data2.xpath('//div[@class="ints-cover"]/img/@alt') # 菜品所需食材 print(ints_names) for dish_name, dish_heat, dish_url in zip(dish_names, dish_heats, dish_urls): # 获取每道菜品的具体网址所需的食材信息 dish_url = f'https://www.haochu.com{dish_url}' response3 = requests.get(url=dish_url, headers=headers) html_data3 = etree.HTML(response3.text) dish_ints_names = html_data3.xpath('//div[@class="ints-cover"]/img/@alt') # 将菜品名、热量、所需食材、具体网址等信息写入到文本文件中 dish = f'{dish_name},{dish_heat},{dish_ints_names},https://www.haochu.com{dish_url}\n' fp.write(dish),我想将 dish_imgs = html_data.xpath('//div[@class="quan_r"]/ul/li/a/img/@src')#菜品图片也加进去
时间: 2024-03-28 21:41:04 浏览: 54
如何将文本转换为UTF-8码 .e.rar
可以将获取的菜品图片链接加入到 `dish` 变量中,最后写入文本文件。修改后的代码如下:
```
with open('./第{}页.txt'.format(i), 'w', encoding='utf-8') as fp:
for num in dish_urls:
new_url = f'https://www.haochu.com{num}'
# 把菜品具体网址作为新url,获取每道菜所需的食材
print(new_url)
response2 = requests.get(url=new_url, headers=headers)
html_data2 = etree.HTML(response2.text)
# 新网址的html——data2
ints_names = html_data2.xpath('//div[@class="ints-cover"]/img/@alt') # 菜品所需食材
dish_imgs = html_data2.xpath('//div[@class="cover-img"]/img/@src') # 菜品图片
print(ints_names)
for dish_name, dish_heat, dish_url, dish_img in zip(dish_names, dish_heats, dish_urls, dish_imgs):
# 获取每道菜品的具体网址所需的食材信息
dish_url = f'https://www.haochu.com{dish_url}'
response3 = requests.get(url=dish_url, headers=headers)
html_data3 = etree.HTML(response3.text)
dish_ints_names = html_data3.xpath('//div[@class="ints-cover"]/img/@alt')
# 将菜品名、热量、所需食材、具体网址、菜品图片等信息写入到文本文件中
dish = f'{dish_name},{dish_heat},{dish_ints_names},https://www.haochu.com{dish_url},{dish_img}\n'
fp.write(dish)
```
阅读全文