1. 程式人生 > >selenium+谷歌無頭瀏覽器爬取網易新聞國內板塊

selenium+谷歌無頭瀏覽器爬取網易新聞國內板塊

quest alt 新聞列表 body lac windows text 分享 encoding

網頁分析

首先來看下要爬取的網站的頁面

技術分享圖片

查看網頁源代碼:你會發現它是由js動態加載顯示的

所以采用selenium+谷歌無頭瀏覽器來爬取它

1 加載網站,並拖動到底,發現其還有個加載更多

技術分享圖片

2 模擬點擊它,然後再次拖動到底,,就可以加載完整個頁面

技術分享圖片

示例代碼
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from time import sleep
from lxml import etree import os import requests # 使用谷歌無頭瀏覽器來加載動態js def main(): # 創建一個無頭瀏覽器對象 chrome_options = Options() # 設置它為無框模式 chrome_options.add_argument(--headless) # 如果在windows上運行需要加代碼 chrome_options.add_argument(--disable-gpu) browser = webdriver.Chrome(chrome_options=chrome_options)
# 設置一個10秒的隱式等待 browser.implicitly_wait(10) browser.get(url) sleep(1) # 翻到頁底 browser.execute_script(window.scrollTo(0,document.body.scrollHeight)) # 點擊加載更多 browser.find_element(By.CSS_SELECTOR, .load_more_btn).click() sleep(1) # 再次翻頁到底 browser.execute_script(
window.scrollTo(0,document.body.scrollHeight)) # 拿到頁面源代碼 source = browser.page_source browser.quit() with open(xinwen.html, w, encoding=utf-8) as f: f.write(source) parse_page(source) # 對新聞列表頁面進行解析 def parse_page(html): # 創建etree對象 tree = etree.HTML(html) new_lst = tree.xpath(//div[@class="ndi_main"]/div) for one_new in new_lst: title = one_new.xpath(.//div[@class="news_title"]/h3/a/text())[0] link = one_new.xpath(.//div[@class="news_title"]/h3/a/@href)[0] write_in(title, link) # 將其寫入到文件 def write_in(title, link): print(開始寫入篇新聞{}.format(title)) response = requests.get(url=link, headers=headers) tree = etree.HTML(response.text) content_lst = tree.xpath(//div[@class="post_text"]//p) title = title.replace(?, ‘‘) with open(new/ + title + .txt, a+, encoding=utf-8) as f: for one_content in content_lst: if one_content.text: con = one_content.text.strip() f.write(con + \n) if __name__ == __main__: url = https://news.163.com/domestic/ headers = {"User-Agent": Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0} if not os.path.exists(new): os.mkdir(new) main()

得到結果:

技術分享圖片

隨意打開一個txt:

技術分享圖片

總結:

1 其實主要的工作還是模擬瀏覽器來進行操作。

2 處理動態的js其實還有其他辦法。

3 爬蟲的方法有好多種,主要還是選擇適合自己的。

4 自己的代碼寫的太爛了。

selenium+谷歌無頭瀏覽器爬取網易新聞國內板塊