python 简单网络爬虫进阶
接上一篇文章,在上一篇文章已经讲解了关于Python安装与配置的相关内容,也实现了一个很简单的爬虫
还不清楚的,这里有直通车可以过去
好了,上一篇中实现了爬取csdn首页的爬虫,但是得到的是许多网页代码,对我们没什么价值,接下来我们处理一下这个爬虫的代码,以实现展示有价值的数据
老规矩,先上代码
# import os
# print("hello world!")
from bs4 import BeautifulSoup
from urllib.request import urlopen
from urllib.request import Request
url="https://www.csdn.net/"
req=Request(url)
content=urlopen(req).read().decode("utf-8")
# print(content)
html = BeautifulSoup(content,"lxml")
floatlis=html.find("div",attrs={"class":"nav_com"}).find_all("li")
for i in range (0,len(floatlis)):
print(floatlis[i].find("a").text)
在Python3中引入bs4模块和urllib,用于请求网页和清洗数据
以上述代码为例
from urllib.request import urlopen
from urllib.request import Request
urlopen Request用于请求网络数据
content=urlopen(req).read().decode("utf-8") #获取到网页源码
将字符格式转换为方便定位的网页标签
html = BeautifulSoup(content,"lxml")
清洗数据,拿到需要的值
floatlis=html.find("div",attrs={"class":"nav_com"}).find_all("li")
将获取到的数组循环输出显示
for i in range (0,len(floatlis)):
print(floatlis[i].find("a").text)
如此就获取到了一个剪刀网页的有效数据了,对弈更复杂的数据获取和清洗,请看下一篇博客