for i in range(1, 6): # 循环遍历 1-5 页 url = f'https://www.haochu.com/caipu/134?page={i}' # 好厨————川菜类菜品网页url response = requests.get(url=url, headers=headers) html_data = etree.HTML(response.text) # 获取川菜类菜品网址的html_data dish_names = html_data.xpath('//div[@class="bei"]/span[1]/text()') # 菜名 dish_heats = html_data.xpath('//div[@class="bei"]/span[2]/text()') # 菜人气度 dish_urls = html_data.xpath('//div[@class="quan_r"]/ul/li/a/@href') # 菜品具体网址 dish_imgs = html_data.xpath('//div[@class="quan_r"]/ul/li/a/img/@src') # 菜品图片 with open('./第{}页.txt'.format(i), 'w', encoding='utf-8') as fp: for dish_name, dish_heat, dish_url in zip(dish_names, dish_heats, dish_urls): # 获取每道菜品的具体网址所需的食材信息 dish_url = f'https://www.haochu.com{dish_url}' response2 = requests.get(url=dish_url, headers=headers) html_data2 = etree.HTML(response2.text) dish_ints_names = html_data2.xpath('//div[@class="ints-cover"]/img/@alt') dish_imgs_url = html_data2.xpath('//div[@class="caipu-detail-cover"]/img/@src') filepath = f'{dish_name}.jpg' response3 = requests.get(url='https:' + ''.join(dish_imgs_url)) for imags in response3: with open(filepath, "wb") as f: f.write(response3.content) # 将菜品名、热量、所需食材、具体网址等信息写入到文本文件中 dish = f' 菜名:{dish_name} 人气度:{dish_heat} 食材:{dish_ints_names} {dish_url}\n' fp.write(dish),我要将图片保存在当前目录的另一个文件夹里
时间: 2024-03-28 10:38:07 浏览: 222
好的,您可以在代码中添加以下内容来保存图片到指定文件夹:
```python
import os
# 创建保存图片的文件夹
if not os.path.exists('./images'):
os.makedirs('./images')
with open('./第{}页.txt'.format(i), 'w', encoding='utf-8') as fp:
for dish_name, dish_heat, dish_url, dish_imgs_url in zip(dish_names, dish_heats, dish_urls, dish_imgs):
# 获取每道菜品的具体网址所需的食材信息
dish_url = f'https://www.haochu.com{dish_url}'
response2 = requests.get(url=dish_url, headers=headers)
html_data2 = etree.HTML(response2.text)
dish_ints_names = html_data2.xpath('//div[@class="ints-cover"]/img/@alt')
dish_imgs_url = html_data2.xpath('//div[@class="caipu-detail-cover"]/img/@src')
# 保存菜品图片到指定文件夹
filepath = f'./images/{dish_name}.jpg'
response3 = requests.get(url='https:' + ''.join(dish_imgs_url))
with open(filepath, "wb") as f:
f.write(response3.content)
# 将菜品名、热量、所需食材、具体网址等信息写入到文本文件中
dish = f' 菜名:{dish_name} 人气度:{dish_heat} 食材:{dish_ints_names} {dish_url}\n'
fp.write(dish)
```
这样修改后,菜品图片会保存在当前目录下的 `images` 文件夹中。
阅读全文