python学习笔记之网络爬虫(七)爬取官网信息标题

T Xiao Ang Zai 11月9号

版本:python3.7

编程软件:sublime

今天我们爬取湖北一所某高校的一个活动的标题。

官网链接:http://www.jwc.hbnu.edu.cn/default.html

爬取链接:http://www.jwc.hbnu.edu.cn/news/153829792548181348.html

上代码:

import urllib.request
import requests
from bs4 import BeautifulSoup

url = "http://www.jwc.hbnu.edu.cn/news/153829792548181348.html"
response = urllib.request.urlopen(url)
html = response.read().decode("GBK")
#print(html)
soup = BeautifulSoup(html,"html.parser")
title = soup.find("div", class_ = "btbt").h3.text.strip()
print(title)

一些知识点之前已经介绍过了,这里说些小技巧:

1.我们得到html会出现是二进制编码的情况,这里我们可以打开网页的审查元素:

输入document.charset就可以看到这个网页的编码了,我们在最后只需解码为该网页编码即可。

2.如何快速查找网页元素:

只需选中在审查元素中查找即可:

3.我们改一下代码,如下:

import urllib.request
import requests
from bs4 import BeautifulSoup

url = "http://www.jwc.hbnu.edu.cn/news/153829792548181348.html"
response = urllib.request.urlopen(url)
html = response.read().decode("GBK")
#print(html)
soup = BeautifulSoup(html,"html.parser")
title = soup.find("div", class_ = "title").text.strip()
title2 = soup.find("div", class_ = "con", id = "contentdisplay").text.strip()
print(title)

下面是效果:

猜你喜欢

转载自blog.csdn.net/ITxiaoangzai/article/details/83904139