|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我想扒学校网站新闻标题,发现结果是乱码,怎么办?
from bs4 import BeautifulSoup
import requests,chardet
url=" "
req = requests.get(url).text
# req.encoding = chardet.detect(req.content)['encoding'] #提取网页编码
soup = BeautifulSoup(req,"html.parser")
newnames = soup.findAll('a')
newtimes = soup.findAll('span',attrs={"class": "time"})
a = 1
for newname in newnames:
for newtime in newtimes:
if newname.string == None:
continue
else:
print(f"学校新闻版块第{a}条标题名称: {newname.string} 发布时间 {newtime.string}")
a+=1
打印结果如下:(标题为乱码)
学校新闻版块第1条标题名称: å­¦æ ¡ä¸»ç«™ 发布时间 2023-08-17
学校新闻版块第2条标题名称: å­¦æ ¡ä¸»ç«™ 发布时间 2023-08-17
学校新闻版块第3条标题名称: å­¦æ ¡ä¸»ç«™ 发布时间 2023-08-16
学校新闻版块第4条标题名称: å­¦æ ¡ä¸»ç«™ 发布时间 2023-08-15
学校新闻版块第5条标题名称: å­¦æ ¡ä¸»ç«™ 发布时间 2023-08-13
学校新闻版块第6条标题名称: å­¦æ ¡ä¸»ç«™ 发布时间 2023-08-13
学校新闻版块第7条标题名称: å­¦æ ¡ä¸»ç«™ 发布时间 2023-08-12
学校新闻版块第8条标题名称: å­¦æ ¡ä¸»ç«™ 发布时间 2023-08-11
学校新闻版块第9条标题名称: å­¦æ ¡ä¸»ç«™ 发布时间 2023-08-11
学校新闻版块第10条标题名称: å­¦æ ¡ä¸»ç«™ 发布时间 2023-08-10
ok,这次加了循环,可以爬以前所有的新闻了
可以给一个最佳答案吗
- from bs4 import BeautifulSoup
- import requests,chardet
- def get(url):
- req = requests.get(url)
- req.encoding="utf-8"
- req=req.text
- # req.encoding = chardet.detect(req.content)['encoding'] #提取网页编码
- soup = BeautifulSoup(req,"html.parser")
- names = soup.findAll('div',class_="list")
- newnames=[a['title'] if 'title' in a.attrs else '' for a in soup.find_all('a')]
- newnames = [name for name in newnames if name!='']s's's's
- newtimes = soup.findAll('span',attrs={"class": "time"})
- a = 1
- for i in range(len(newnames)):
- if newnames[i] == None:
- continue
- else:
- try:
- print("学校新闻版块第",i,"条标题名称:\t",newnames[i]," 发布时间 ",newtimes[i].text)
- a+=1
- except:
- pass
- get("https://news.wtu.edu.cn/xxxw.htm")
- for j in range(295):
- if 294-j!=0:
- j=294-j
- else:
- break
- get("https://news.wtu.edu.cn/xxxw/"+str(j)+".htm")
复制代码
|
|