python3爬虫(基于requests、BeautifulSoup4)之项目实战(一)

python3爬虫(基于requests、BeautifulSoup4)之项目实战

1.项目简述:
操作系统:windows10
所需软件:pycharm(社区、专业版均可)
python版本:个人使用python 3.7.0
我抓取的是母校教务处网站首页的新闻内容
母校教务处网站链接:http://jwc.tyut.edu.cn/
2.具体操作:
首先打开pycharm 新建python项目,创建一个TYUT.py;
之后导入requests、BeautifulSoup4库就可以开始爬虫之旅了。
具体导入方法:

import requests
from bs4 import BeautifulSoup

爬虫首先解决的问题应该是获取网页全部内容
这时候应该用Chrome开发工具对目标网页有一个简单的分析
这里写图片描述
明确了网页的请求方法是request.get后就可以写代码了

import requests
from bs4 import BeautifulSoup

def getInfo(url):
    res=requests.get(url)
    res.encoding='utf-8'
    print(res.text)

if __name__ == '__main__':
    url='http://jwc.tyut.edu.cn/'
    getInfo(url)

这一步可以将目标网页的html连同标签全部放到res下,同时为了防止乱码要指定返回内容编码为utf-8
这时候我们可以执行一下代码,返回结果部分如下:
这里写图片描述
这时候我们要知道返回内容带有许多html标签,我们要将标签去除,这时候就要用到BeautifulSoup了

import requests
from bs4 import BeautifulSoup

def getInfo(url):
    res=requests.get(url)
    res.encoding='utf-8'
    soup=BeautifulSoup(res.text,'html.parser')
    print(soup.text)

if __name__ == '__main__':
    url='http://jwc.tyut.edu.cn/'
    getInfo(url)

打印一下我们发现这时返回数据只有文本内容了,结果部分如下:
这里写图片描述

今天实战就到这里,下期再见

猜你喜欢

转载自blog.csdn.net/weixin_38168694/article/details/81270739