一.利用pandas库直接存储为Excel文件;
主要技术点:
1.首先建立列表,存储每一次爬取的内容,为后面的字典存储做准备;
2.利用字典格式储存数据;
3. 利用pandas中DataFrame()函数保存字典数据 并利用to_excel()函数储存到exel表格中;
应用举例一:(菜鸟教程python100例url
)
from lxml import etree
import requests#导入请求库
import pandas as pd #导入pandas库直接存为exel文件
#菜鸟教程python100例url
recommed_url='https://www.runoob.com/python3/python3-examples.html'
#利用requests的get()方法请求url 并利用decode()方法以'utf-8'解码
res=requests.get(url=recommed_url).content.decode('utf-8')
#利用etree库解析返回的HTML页面
ele=etree.HTML(res)
#利用Xpath()提取详情页的URl
elements=ele.xpath('//*[@id="content"]/ul/li/a/@href')
#利用列表存储所有的URL
url_list=['https://www.runoob.com/python3/'+ele for ele in elements]
url = url_list
#print()输出语句查看解析的详情页url
# print(url_list)
#利用列表存储每一次爬取的内容 为后面的字典存储做准备
title=[]
url = []
body=[]
content = []
#解析详情页的函数
for url in url_list:
print(url)
res2 = requests.get(url).content.decode('utf-8')
ele2=etree.HTML(res2)
title.append(ele2.xpath('//*[@id="content"]/h1/text()')[0])
body.append(ele2.xpath('//*[@id="content"]/p[2]/text()')[0])
#利用字典的格式存储数据
data={
'文章标题':title,
'文章url':url,
'题目内容':body,
}
#利用pandas中DataFrame()函数保存字典数据 并利用to_excel()函数储存到exel表格中
df=pd.DataFrame(data)
df.to_excel('cainiao3.xlsx',encoding='utf-8')
函数封装版:
import requests
from lxml import html
etree = html.etree #解决lxml模块导入etree有误
import pandas as pd
#利用列表存储每一次爬取的内容 为后面的字典存储做准备
title=[]
url = []
body=[]
content = []
# 解析列表页的函数
def get_url_info(recommed_url):
#利用requests的get()方法请求url 并利用decode()方法以'utf-8'解码
res=requests.get(recommed_url).content.decode('utf-8')
#利用etree库解析返回的HTML页面
ele=etree.HTML(res)
#利用Xpath()提取详情页的URl
elements=ele.xpath('//*[@id="content"]/ul/li/a/@href')
#利用列表存储所有的URL
url_list=['https://www.runoob.com/python3/'+ele for ele in elements]
#url_list
# for url in url_list:
# print(url)
get_url_cainiao(url_list)
#print()输出语句查看解析的详情页url
# print(url_list)
# 解析详情页的函数
def get_url_cainiao(url_list):
for url in url_list:
print(url)
res2 = requests.get(url).content.decode('utf-8')
ele2 = etree.HTML(res2)
title.append(ele2.xpath('//*[@id="content"]/h1/text()')[0])
body.append(ele2.xpath('//*[@id="content"]/p[2]/text()')[0])
# 利用字典的格式存储数据
data = {
'文章标题': title,
'文章url': url,
'题目内容': body,
}
# 利用pandas中DataFrame()函数保存字典数据 并利用to_excel()函数储存到exel表格中
df = pd.DataFrame(data)
df.to_excel('cainiao0.xlsx', encoding='utf-8')
#主函数程序主入口
if __name__ == '__main__':
recommed_url = 'https://www.runoob.com/python3/python3-examples.html'
get_url_info(recommed_url)