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

时间:2018-11-20 21:47:07

标签: python python-3.x selenium geckodriver

我正在测试下面的代码。

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'))

这可以很好地登录到我的公司Intranet,但是它仅打印非常非常基本的信息。按下F12键可显示页面上的许多数据都是使用JavaScript呈现的。我对此进行了一些研究,并试图找到一种方法来真正抓取我在屏幕上看到的内容,而不是非常清晰地看到的内容。有什么方法可以对页面上显示的所有数据进行大数据转储?谢谢。

2 个答案:

答案 0 :(得分:1)

您打开2个浏览器,删除此行

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

问题出在登录的硒中,而不是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'))

答案 1 :(得分:0)

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

“隐式等待”使您可以选择特定的等待时间,然后再进行抓取。

“显式等待”使您可以选择要等待的事件,例如可见或可单击的特定元素。

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

相关问题