Selenium Webscraping JavaScript 元素

Selenium Webscraping JavaScript elements

我正在尝试使用 selenium 和 PhantomJS 来抓取 JavaScript 产生的一些元素。

我的代码:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select

from bs4 import BeautifulSoup
from selenium import webdriver
from collections import OrderedDict
import time

driver = webdriver.PhantomJS()
driver.get('http://www.envirostor.dtsc.ca.gov/public/profile_report?global_id=01290021&starttab=landuserestrictions')

driver.find_element_by_id('sitefacdocsTab').click()
time.sleep(5)

html = driver.page_source
soup = BeautifulSoup(html)

单击操作后,我仍然得到旧页面数据,而不是 jQuery 给出的新数据。

使用requests

在浏览器中打开开发者工具 > 网络 > XHR 选项卡。然后,单击 Site/Facility Docs 选项卡。您会在 XHR 选项卡中看到一个 AJAX 请求。请求发送到 this site 以获取选项卡数据。

只需使用 requests 模块,您就可以从该选项卡中抓取任何内容。

import requests

r = requests.get('http://www.envirostor.dtsc.ca.gov/public/profile_report_include?global_id=01290021&ou_id=&site_id=&tabname=sitefacdocs&orderby=&schorderby=&comporderby=&rand=0.07839738919075079&_=1521609095041')
soup = BeautifulSoup(r.text, 'lxml')

# And to check whether we've got the correct data:
table = soup.find('table', class_='display-v4-default')
print(table.find('a', target='_documents').text)
# Soil Management Plan Implementation Report, Public Market Infrastructure Relocation, Phase 1-B Infrastructure Area

使用Selenium

当您想等待页面加载时,您应该永远不要使用time.sleep()。您应该改用 Eplicit Waits。使用后,您可以使用 .get_attribute('innerHTML') 属性.

获取整个选项卡内容
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('http://www.envirostor.dtsc.ca.gov/public/profile_report?global_id=01290021&starttab=landuserestrictions')

driver.find_element_by_id('sitefacdocsTab').click()
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, 'docdatediv')))

html = driver.find_element_by_id('sitefacdocs').get_attribute('innerHTML')
soup = BeautifulSoup(html, 'lxml')
table = soup.find('table', class_='display-v4-default')
print(table.find('a', target='_documents').text)
# Soil Management Plan Implementation Report, Public Market Infrastructure Relocation, Phase 1-B Infrastructure Area

附加信息:

带有 id="docdatediv" 的元素是包含日期范围过滤器的 div 标签。我已经使用它,因为它不存在于第一个选项卡上,但存在于您想要的选项卡上。您可以将任何此类元素用于 WebDriverWait.

并且,带有 id="sitefacdocs" 的元素是 div 标签,它包含整个选项卡内容(即日期过滤器和下面的所有表格)。因此,您的 soup 对象将包含所有这些内容。