(1)目標網站為:https://www.qiushibaike.com/text/
(2)爬取目標網站10頁內容
(3)爬取內容包括:作者和內容
(4)保存在字典中,格式如下:
{
1:{ '作者':',,,',
'內容':',,,,,,',
}
……
}
(5)將內容轉換為JSON保存在文本中
1,首先對網頁url進行分析確定前10頁的url.
2,參考 requests bs4 json庫,
3,寫主函式 主函式下面有 請求url的函式 將 內容 作為引數交給 bs4 做處理(需要確定網頁標簽) 得到最終資料 做持久化保存,
import requests
from bs4 import BeautifulSoup as BS
import json
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36"
}
#ua偽裝
text='https://www.qiushibaike.com/text'
count_num=1
def get_html(url):
html=requests.get(url,headers=headers)
#請求url
return html.text
#回傳整頁的資料,請求多少頁回傳多少頁的資料,
def bs_html(text_content,content_dict):
global count_num
soup=BS(text_content,'html.parser')
#是要bs庫里面的html.parser方法對text_content進行排序(text_content就是爬取的頁面的html)
soup_list=soup.select('#content .article ')
#使用bs里的select這個方法找到頁面里面標簽,
for item in soup_list:
#回圈這個整體標簽(這是整個頁面,我們需要里面的某些資料)
biaoti=item.select_one('.author a h2')
#item作為臨時變數,每回圈一次都要在里面提取出整體標簽下的 h2 標簽,這個就是標題,賦值給前面biaoti這個變數
if biaoti:
biaoti = biaoti.text.strip()
else:
biaoti='匿名用戶'
content=item.select_one('a .content span').text.strip()
#整體標簽下的內容也是上述方法,提取出來
content_dict[count_num]={'作者':biaoti,'內容':content}
#使用這個空字典 前面加上計數器 后面是字典形式 每回圈一次對應的計數+1
count_num += 1
return content_dict
#回傳整個字典
def save_text(text_list):
#保存檔案函式
with open('rut.txt','w',encoding='utf8')as f:
#這個檔案不存在 以寫的方式打開就自動創建 起個別名f
f.write(text_list)
#對f進行保存 保存處理后的字典
f.close()
#保存后關閉檔案
def main(num):
content_dict={}
#定義空字典
for i in range(1,num+1):
#回圈次數 num是形參
url=text+'/page{}/'.format(i)
#最終的url 對初始的url進行拼接 ,最終得到10頁子url
text_content=get_html(url)
#對url請求,回傳的資料賦值給 text_content這個變數,作為bs函式的引數,
text_list=bs_html(text_content,content_dict)
#bs函式對整體的網頁資料,空字典進行處理,當作兩個引數放進去,上面bs函式處理好后回傳整個字典,賦值給text_list這個變數
save_text(json.dumps(text_list,ensure_ascii=False))
#對資料保存前還要進行處理,引數是bs處理后的字典 去掉ascii這個編碼格式,保存時使用utf8格式
if __name__ == '__main__':
main(10)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/144271.html
標籤:Python
