2

利用docker实现命令行下使用浏览器渲染js网页

 2 years ago
source link: https://www.bobobk.com/525.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

利用docker实现命令行下使用浏览器渲染js网页

2021年12月8日

| 技术

在使用scrapy爬取网页时,由于很多网站采用js渲染的方式,直接诶获取源代码是获取不到需要的网页内容的,此时往往采用selenium驱动浏览器来获取网页内容非常合适。但是有一个问题就是这种情况下需要本地安装浏览器,还非的用非root运行,于是采用docker的方式提供服务chrome服务,并采用selenium驱动获取渲染后的网页内容。

运行chrome的docker容器

通过搜索知道docker hub上容器是selenium/standalone-chrome,在本地已经安装了docker的情况下,直接将该服务运行与14444号端口上,这里安全起见,只允许本地访问。

docker run -itd --name=chrome  -p 127.0.0.1:14444:4444 --shm-size="2g" selenium/standalone-chrome

参数非常简单,只配置了后端运行,端口映射,shm大小

selenium 调用远程服务抓取网页

selenium 的webdrive有Remote参数指定远程地址

from selenium import webdriver
from scrapy.selector import Selector
options = webdriver.ChromeOptions()
options.add_argument('--headless')  # example
driver = webdriver.Remote("http://127.0.0.1:14444/wd/hub", options=options)
driver.get("https://www.bobobk.com")
hrefs = Selector(text=driver.page_source).xpath("//article/header/h1/a/@href").extract()
for  url in hrefs:
    print(url)
#https://www.bobobk.com/833.html
#https://www.bobobk.com/621.html
#https://www.bobobk.com/852.html
#https://www.bobobk.com/731.html
#https://www.bobobk.com/682.html
#https://www.bobobk.com/671.html
#https://www.bobobk.com/523.html
#https://www.bobobk.com/521.html
#https://www.bobobk.com/823.html
#https://www.bobobk.com/512.html

示例中采用本网站作为目标,实际验证中使用javascript渲染的网站均可完美抓取

采用docker形式提供浏览器的服务,可以很好地解决网页是由js实时渲染从而导致无法获取需要的网页内容欧冠你的问题。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK