selenium+chrome抓取JS动态渲染页面

selenium+chrome抓取JS动态渲染页面

一个小例子:

#需要安装Python的selenium包
#本地安装Chrome浏览器和对应的Webdriver
#一个抓取JS动态渲染页面的小例子

from selenium import webdriver
import time
from selenium.webdriver.support import expected_conditions as EC
options = webdriver.ChromeOptions()
options.add_argument('--headless')  #采用无头模式
options.add_argument('--disable-gpu')  #采用无头模式
options.add_argument('--log-level=3')
options.add_argument('--disable-features = RendererCodeIntegrity') #禁用渲染器代码完整性保护功能,防止chrome浏览器出现 'Aw, snap!'的崩溃错误
options.add_argument("--no-sandbox")  #若依然出现崩溃错误,加上此设置
#options.add_argument("--proxy-server=")  #内网机器设置代理
web = webdriver.Chrome(options = options)
web.get("http://news.mydrivers.com/")
time.sleep(2)
web.execute_script("window.scrollBy(0,2000)") #执行动作
time.sleep(2)  #等待2s
web.execute_script("window.scrollBy(0,4000)")
time.sleep(2)
input = web.find_element_by_class_name("more")  #按钮:查看更多
input.click()
more = web.find_element_by_xpath('//div[@id="assist"]')
more.click()
time.sleep(2)
h3 = web.find_elements_by_xpath('//ul[@id="newsleft" and @class="news_lb"]/li/h3/a')  #找出页面新闻链接
print(len(h3))
#for h in h3:
#    print(h.get_attribute('href'))
web.close()

你可能感兴趣的:(爬虫)