爬虫流程.png
获取网页信息
import urllib.request
url = 'https://www.douban.com'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36 '
} ###模拟游览器headers请求信息,可放入更多信息,逼真模拟,以字典键值对加入
req = urlliba.request.Request(url = url,headers = headers ) ##将请求信息进行封装
response = urllib.request.urlopen(req) ###打开获取网页信息print(response.read().decode('utf-8')) ###打印信息,utf-8解码,可以将中文正常显示
解析网页信息
BeautifulSoup 将复杂的HTML文档转换成一个复杂的树形结构。
四种对象:
tag ###标签
NavigableString ###标签里的内容
BeautifulSoup ###表示整个文档
comment ###特殊的NavigableString,输出不带注释
from bs4 import BeautifulSoup
file = open('./baidu,html','rb') ##二进制打开已获取的网页html文件
html = file.read() #读取
bs = BeautifulSoup(html,'html.parser') ###解析html对象,以'html.parser'方式,可选择多种方式
print(bs.a) ###打印标签和内容,只打印第一个(tag)
print(bs.a.string) ###只打印内容 (NavigableString)
print(bs.a.attrs) ###获取标签的所有属性,返回字典
print(bs) #####(BeautifulSoup对象)
#####文档的遍历
print(bs.head.contents) ###contents 获取tag的所有子节点返回一个列表,获取子节点还有很多方法,搜索文档
####文档的查询
t_list = bs.find_all('a')##find_all() 查找所有与字符串完全匹配的内容,返回list
t_list = bs.find_all(re.complile('a')) ##包含a的内容
t.list = bs.find_all('a',limit = 3) ###限制3个
###css选择器
print(bs.select('title')) ##查找标签
t_list = bs.select('.mnav') ##通过类名查找
t_list = bs.select('#u1') ##通过id查找
t_list = bs.select('head > title') ##通过子标签查找
保存数据
import xlwt #进行excel操作
workbook = xlwt.Workbook(encoding='utf-8') ###创建workbook对象
worksheet = workbook.add_sheet('sheet1') ###创建工作表
for i in range(0,9):
for j in range(0,i+1):
worksheet.write(i,j,'%d * %d = %d'%(i+1,j+1,(i+1)*(j+1)))
workbook.save('test.xls') ###保存excel表