一.利用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)