加上文件保存文件名为shimeng
时间: 2024-03-15 08:42:50 浏览: 10
以下是将世萌女性组别选手数据保存到文件的示例代码,需要使用Python爬虫框架Scrapy:
```python
import scrapy
class ShimoSpider(scrapy.Spider):
name = 'shimo'
allowed_domains = ['www.saimoeofficial.com']
start_urls = ['http://www.saimoeofficial.com/vote.html']
def parse(self, response):
# 获取女性组别的选手列表
player_list = response.xpath('//div[@id="list_f"]/div[@class="list"]/ul/li')
for player in player_list:
# 获取选手姓名和照片链接
name = player.xpath('a/text()').get()
photo_url = player.xpath('a/img/@src').get()
# 构造选手数据对象
data = {
'name': name,
'photo_url': photo_url,
}
# 输出选手数据
yield data
# 将数据保存到文件
filename = 'shimeng.txt'
with open(filename, 'w', encoding='utf-8') as f:
for data in player_list:
f.write(f"{data['name']}\t{data['photo_url']}\n")
```
在`parse`方法中,我们使用`yield`输出了选手数据,并在方法结尾处添加了将数据保存到文件的代码,将选手数据写入`shimeng.txt`文件中。文件保存的方式可以根据实际需求进行修改。