使用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 对象将有所有这些东西要刮掉。