python获取网页内容

需要用到bs4套件来获取网页中的文本,如果没有添加此套件,可以根据以下操作来添加win+r,输入cmd,输入pip install BeautifulSoup4,因为我已经安装过了所以出现以下内容

  安装完成后即可开始编写代码

代码如下
 
 1 import requests
 2 #导入bs4套件
 3 from bs4 import BeautifulSoup
 4 newsurl = 'http://www.163.com/'
 5 #发送get请求
 6 res = requests.get(newsurl)
 7 #设置网页编码格式,如果不设置的话会产生中文乱码,编码格式按照爬取得网页来设置
 8 res.encoding='gbk'
 9 #将网页放入BeautifulSoup中,获取网页中的文本内容,把html标签都除掉,html.parser为剖析器,如果不自己设置系统会自动分配一个剖析器
10 soup = BeautifulSoup(res.text,"html.parser")
11 print(res.text)
 
 

猜你喜欢

转载自blog.csdn.net/qq_36750461/article/details/81200021