廿伍-爬蟲接受JS渲染

1. 開始

研究了好久,終于發(fā)現(xiàn)了如何做,不過無法異步完成,只能用 Supervisor 開多進程去做了。

2.使用 selenium 渲染JS

首先我必須放出參考文章

實在參考太多了,不能一步步來了。
嘗試過很多種 JS渲染 的方式,最后還是選擇了 selenium ,然后后來為了安裝那個 chromedriver 也花費了很大力氣,現(xiàn)在叫我重來一遍我也真忘了怎么做了。
以下是單一請求的代碼:

# 測試新方法
from selenium import webdriver 
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time

# 各種設(shè)置及配置,可參考上述鏈接
options= Options()
options.add_argument('--no-sandbox')
options.add_argument('--disable-gpu')
options.add_argument('--hide-scrollbars') 
options.add_argument('blink-settings=imagesEnabled=false') 
options.add_argument('--headless') 
options.add_argument('--incognito')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--disable-software-rasterizer')
options.add_argument('--disable-extensions')
options.add_argument('--user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36"')
options.add_argument('--window-size=1280x1024')
options.add_argument('--start-maximized')
options.add_argument('--disable-infobars')
# options.add_argument("–proxy-server=http://ip:端口")

# ChromeDriver 也是一個坑,安裝也是參照上述某個鏈接
browser = webdriver.Chrome('/usr/bin/chromedriver',chrome_options = options)
# 可以參照官網(wǎng) API 
browser.set_page_load_timeout(20)
browser.set_script_timeout(20)
browser.implicitly_wait(20) 
browser.get('https://weibo.com/1239160407/GcSidx58Y')
# 等待JS運行完及各種跳轉(zhuǎn)
time.sleep(10)
html=browser.page_source
# 必須退出,不然瀏覽器進程會駐留
browser.close()
browser.quit()
soup = BeautifulSoup(html, 'lxml')
import re
# 爬微博必須 div 爬
data = soup.select('div')
for item in data:
    result =  item.get_text()
    strOut=''
    strOut=re.sub('\n+', '\n', result)
    if len(strOut)>10 :
        print(strOut)

3. 后續(xù)工作

  • 為交互界面頁增加刪減含某些關(guān)鍵字的內(nèi)容。
  • 增加展示數(shù)據(jù)庫數(shù)據(jù)量的頁面
  • 有可能寫專題爬蟲,如微博或者其他
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容