python动态网页爬虫

在用python爬取动态网页的时候,有些网页的HTML代码是由javascript动态生成的,直接爬取可能会出现无法加载的情况,需要用phantomJS和selenium模拟浏览器,之后再爬取。

安装准备

一.下载phantomJS压缩包,解压,注意路径./bin/phantomjs.exe,里面有各种浏览器的驱动。

二.pip install selenium安装selenium

例子

#爬取javacodeexample网站某网页中的url列表

from bs4 import BeautifulSoup
from selenium import webdriver
import time
url = 'https://www.programcreek.com/java-api-examples/?ClassName=lucene&action=search&submit=Search'
sleep_time = 10

#参数为phantomjs压缩包下./bin/phantomjs.exe的路径
driver = webdriver.PhantomJS(executable_path=r'E:\Downloads\phantomjs-2.1.1-windows\phantomjs-2.1.1-windows\bin\phantomjs.exe')

driver.set_window_size(1920, 1080)
driver.get(url)
time.sleep(sleep_time)
page = BeautifulSoup(driver.page_source)
result=page.find_all("div",attrs={"id":"api-list-apiname"})
f = open('lucene-url.txt', 'w')
for res in result:
    re = res.find('a')
    f.writelines(re['href'])
    f.writelines("\n")