python 爬蟲(chóng)如何爬取動(dòng)態(tài)生成的網(wǎng)頁(yè)內(nèi)容
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
【背景】 對(duì)于網(wǎng)頁(yè)信息的采集,靜態(tài)頁(yè)面我們通常都可以通過(guò)python的request.get()庫(kù)就能獲取到整個(gè)頁(yè)面的信息。 但是對(duì)于動(dòng)態(tài)生成的網(wǎng)頁(yè)信息來(lái)說(shuō),我們通過(guò)request.get()是獲取不到。 【方法】 可以通過(guò)python第三方庫(kù)selenium來(lái)配合實(shí)現(xiàn)信息獲取,采取方案:python + request + selenium + BeautifulSoup 我們拿縱橫中文網(wǎng)的小說(shuō)采集舉例(注意:請(qǐng)查看網(wǎng)站的robots協(xié)議找到可以爬取的內(nèi)容,所謂盜亦有道): 思路整理: 1.通過(guò)selenium 定位元素的方式找到小說(shuō)章節(jié)信息 2.通過(guò)BeautifulSoup加工后提取章節(jié)標(biāo)題和對(duì)應(yīng)的各章節(jié)的鏈接信息 3.通過(guò)request +BeautifulSoup 按章節(jié)鏈接提取小說(shuō)內(nèi)容,并將內(nèi)容存儲(chǔ)下來(lái) 【上代碼】 1.先在開(kāi)發(fā)者工具中,調(diào)試定位所需元素對(duì)應(yīng)的xpath命令編寫方式 2.通過(guò)selenium 中find_elements()定位元素的方式找到所有小說(shuō)章節(jié),我們這里定義一個(gè)方法接受參數(shù)來(lái)使用 def Get_novel_chapters_info(url:str,xpath:str,skip_num=None,chapters_num=None): # skip_num 需要跳過(guò)的采集章節(jié)(默認(rèn)不跳過(guò)),chapters_num需要采集的章節(jié)數(shù)(默認(rèn)全部章節(jié))# 創(chuàng)建Chrome選項(xiàng)(禁用圖形界面)chrome_options = Options() chrome_options.add_argument("--headless") driver = webdriver.Chrome(options=chrome_options) driver.get(url) driver.maximize_window() time.sleep(3) # 采集小說(shuō)的章節(jié)元素catalogues_list = [] try: catalogues = driver.find_elements(By.XPATH,xpath) if skip_num is None: for catalogue in catalogues: catalogues_list.append(catalogue.get_attribute('outerHTML')) driver.quit() if chapters_num is None: return catalogues_list else: return catalogues_list[:chapters_num] else: for catalogue in catalogues[skip_num:]: catalogues_list.append(catalogue.get_attribute('outerHTML')) driver.quit() if chapters_num is None: return catalogues_list else: return catalogues_list[:chapters_num] except Exception: driver.quit() 3.把采集到的信息通過(guò)beautifulsoup加工后,提取章節(jié)標(biāo)題和鏈接內(nèi)容 # 獲取章節(jié)標(biāo)題和對(duì)應(yīng)的鏈接信息title_link = {} for each in catalogues_list: bs = BeautifulSoup(each,'html.parser') chapter = bs.find('a') title = chapter.text link = 'https:' + chapter.get('href') title_link[title] = link 4.通過(guò)request+BeautifulSoup 按章節(jié)鏈接提取小說(shuō)內(nèi)容,并保存到一個(gè)文件中 # 按章節(jié)保存小說(shuō)內(nèi)容novel_path = '小說(shuō)存放的路徑/小說(shuō)名稱.txt' with open(novel_path,'a') as f: for title,url in title_link.items(): response = requests.get(url,headers={'user-agent':'Mozilla/5.0'}) html = response.content.decode('utf-8') soup = BeautifulSoup(html,'html.parser') content = soup.find('div',class_='content').text # 先寫章節(jié)標(biāo)題,再寫小說(shuō)內(nèi)容f.write('---小西瓜免費(fèi)小說(shuō)---' + '\n'*2) f.write(title + '\n') f.write(content+'\n'*3) 五分鐘學(xué)個(gè)小技能,作者:潘_談,轉(zhuǎn)載請(qǐng)注明原文鏈接:https://www.cnblogs.com/123gogogo/p/18517392 該文章在 2024/11/2 10:05:21 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |