如何正确抓取基于 JavaScript 的站点?

How to correctly scrape a JavaScript-based site?

我正在测试下面的代码。

from bs4 import BeautifulSoup
import requests
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
import time

browser = webdriver.Firefox(executable_path="C:/Utility/geckodriver.exe")
wd = webdriver.Firefox(executable_path="C:/Utility/geckodriver.exe", firefox_profile=profile)
url = "https://corp_intranet"
wd.get(url)

# set username
time.sleep(2)
username = wd.find_element_by_id("id_email")
username.send_keys("my_email@corp.com")

# set password
password = wd.find_element_by_id("id_password")
password.send_keys("my_password")


url=("https://corp_intranet")
r = requests.get(url)
content = r.content.decode('utf-8')
print(BeautifulSoup(content, 'html.parser'))

这可以正常登录到我的公司内部网,但它只打印非常非常基本的信息。按 F12 显示页面上的很多数据是使用 JavaScript 呈现的。我对此做了一些研究,并试图找到一种方法来真正抓住我在屏幕上看到的东西,而不是我能看到的非常非常稀释的版本。有没有办法对页面上显示的所有数据进行大数据转储?谢谢

您需要让 Selenium 通过隐式或显式等待来等待网页加载其他内容。

隐式等待可让您选择在抓取之前等待的特定时间。

显式等待让您选择要等待的事件,例如特定元素可见或可点击。

This answer 详细介绍了这个概念。

你打开2个浏览器删除这行

browser = webdriver.Firefox(executable_path="C:/Utility/geckodriver.exe")

问题出在您已登录的 selenium 中,但未登录 requests,因为它使用不同的会话

.....
.....
# missing click button? add "\n" to submit or click the button
password.send_keys("my_password\n")

# wait max 10 seconds until "theID" visible in Logged In page
WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.ID, "theID")))

content = wd.page_source
print(BeautifulSoup(content, 'html.parser'))