这是什么字符编码错误啊,改怎么解决呢能够大致讲解一下吗
文件里有几行乱打的文字,格式从docx到txt都不行
【相关推荐】
#加载需要的库
import requests
from bs4 import BeautifulSoup
from lxml import etree
f = open("C:\\Users\LeeChoy\Desktop\kuwomusic.txt",'w+',encoding='utf-8') #打开文件
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'} ##从浏览器复制张贴时注意删除agent:后面的空格
responce = requests.get("http://www.kuwo.cn/bang/index",headers=headers) ##为使抓取数据稳定,伪装成浏览器
soup = BeautifulSoup(responce.text,'html.parser') #BeautifulSoup解析网页
html = etree.HTML(responce.text) #XPath解析
#利用选择器获得数据
# 一、获得榜单的名字
names = soup.select( '#chartsContent > div.rightContentBox > ul > li > div.name > a')
#二、获取歌曲歌手
singers = soup.select('#chartsContent > div.rightContentBox > ul > li > div.artist > a')
#三、获取歌手的热度 xpath解析获得为一个列表
heats = html.xpath('//*[@id="chartsContent"]/div[2]/ul/li/div[4]/div/@style')
i=0 #为了写序号以及便于列表输出和储存数据
for name ,singer, heat in zip(names,singers,heats):
print((str)(i+1)+" "+name.get_text()+" "+singer.get_text()+" "+heats[i].replace("width:",""))
f.write((str)(i + 1) + " " + name.get_text() + " "+singer.get_text() + " "+heats[i].replace("width:","")+'\n')
i+=1
f.close() #关闭文件
①打印的爬取结果
②写入的TXT文件