帮我修改一下代码, with open('./第{}页.txt'.format(i), 'w', encoding='utf-8') as fp: for num in dish_urls: new_urls=f'https://www.haochu.com{num}' #把菜品具体网址作为新url,获取每道菜所需的食材 print(new_urls) response2=requests.get(url=new_urls,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 = f'{dish_name},{dish_heat},{ints_names},https://www.haochu.com{dish_url}\n' fp.write(dish),为什么ints_names只有一个
时间: 2024-03-29 12:36:32 浏览: 64
可以将第二个 for 循环嵌套在第一个循环中,这样就可以在每个菜品的具体网址上重新解析获取到该菜品所需的食材信息,然后将所有的信息写入到文本文件中。修改后的代码如下:
```
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)
```
这样修改后,ints_names 就会在每个菜品的具体网址上重新解析获取到该菜品所需的食材信息,从而可以正确地将所有的信息写入到文本文件中。
阅读全文