您的位置首页生活百科

python爬虫BeautifulSoup的简单使用

python爬虫BeautifulSoup的简单使用

的有关信息介绍如下:

python爬虫BeautifulSoup的简单使用

BeautifulSoup用来解析 html网页,虽然效率较低,但是使用十分简便

点击开始--运行,输入cmd命令,打开windows命令行窗口

使用pip安装BeautifulSoup包

pip install BS4

打开python开发工具IDLE,新建‘bstest.py’文件,并代码如下:

from bs4 import BeautifulSoup

import urllib.request

s = urllib.request.urlopen('http://www.baidu.com')

print (type(s.read()))

F5运行代码,打印出返回结果类型,为bytes

修改代码,将响应传入创建一个BeautifulSoup对象,这样就可以解析了,注意不要使用read方法,代码如下:

from bs4 import BeautifulSoup

import urllib.request

s = urllib.request.urlopen('http://www.baidu.com')

so = BeautifulSoup(s,'html.parser')

使用创建的BeautifulSoup对象打印网页的title,代码如下:

from bs4 import BeautifulSoup

import urllib.request

s = urllib.request.urlopen('http://www.baidu.com')

so = BeautifulSoup(s,'html.parser')

print (so.title)

F5运行代码打印出网页的title,正确解码成中文,这就是beautifulsoup的魅力