ARTICLE · 1412896
第七次课程序代码,直接复制运行
第七次课程序代码,直接复制运行
第一个程序:测试豆瓣网站
import requestsfrom bs4 import BeautifulSoupurl=input('请输入您要爬取的网址:') #动态输入网址r=requests.get(url) #向网站服务器发送请求print(r.status_code)r.encoding=r.apparent_encoding #修改编码方式html=r.text #网页的源代码soup=BeautifulSoup(html,'html.parser') #解析源代码text=soup.get_text().replace('\n\n','') #得到源代码中的文本数据print(text) #输出文字内容title=soup.title.text#得到title标签的内容print(title) #输出文字内容with open(title+".txt","w",encoding=r.encoding,errors='ignore') as f:f.write(text)#将爬取的小说写进记事本文件中#测试爬取豆瓣文学作品
第二个程序:加入代理再测试爬取豆瓣
import requestsfrom bs4 import BeautifulSoupurl=input('请输入您要爬取的网址:') #动态输入网址headers = {'User-Agent':'*'}#设置用户代理https://www.douban.com/r=requests.get(url,headers=headers) #向网站服务器发送请求print(r.status_code)r.encoding=r.apparent_encoding #修改编码方式html=r.text #网页的源代码soup=BeautifulSoup(html,'html.parser') #解析源代码text=soup.get_text().replace('\n\n','') #得到源代码中的文本数据print(text) #输出文字内容title=soup.title.text#得到title标签的内容print(title) #输出文字内容with open(title+".txt","w",encoding=r.encoding,errors='ignore') as f:f.write(text)#将爬取的小说写进记事本文件中
第三个程序:修改文件名字符爬取《肖申克的救赎》
import requestsfrom bs4 import BeautifulSoupurl=input('请输入您要爬取的网址:') #动态输入网址headers = {'User-Agent':'*'}#设置用户代理https://www.douban.com/r=requests.get(url,headers=headers) #向网站服务器发送请求print(r.status_code)if r.status_code==200:print('恭喜您!爬取成功!')else:print('很遗憾!爬取失败了!')exit()#退出程序r.encoding=r.apparent_encoding #修改编码方式non_bmp = dict.fromkeys(range(0x010000, 0x10FFFF))#去掉乱起八糟的字符html=r.text.translate(non_bmp) #网页的源代码soup=BeautifulSoup(html,'html.parser') #解析源代码text=soup.get_text().replace('\n\n','') #得到源代码中的文本数据print(text) #输出文字内容asc= dict.fromkeys(range(0x00000, 0x0007F))#去掉ASCII码字符title=soup.title.text.translate(asc) #得到title标签的内容print(title) #输出文字内容with open(title+".txt","w",encoding=r.encoding,errors='ignore') as f:f.write(text)#将爬取的小说写进记事本文件中#https://movie.douban.com/subject/1292052/comments















































































