Selenium 是解决该问题的好方法,但已被接受的答案已被弃用。正如@Seth 在 Firefox/Chrome(或可能的其他浏览器)的 cmets 无头模式中提到的那样,应该使用而不是 PhantomJS。
首先你需要下载特定的驱动程序:
Geckodriver for Firefox
ChromeDriver for Chrome
接下来,您可以将下载的驱动程序的路径添加到系统 PATH 变量中。但这不是必需的,您也可以在代码中指定可执行文件所在的位置。
火狐:
from bs4 import BeautifulSoup
from selenium import webdriver
options = webdriver.FirefoxOptions()
options.add_argument('--headless')
# executable_path param is not needed if you updated PATH
browser = webdriver.Firefox(options=options, executable_path='YOUR_PATH/geckodriver.exe')
browser.get("http://legendas.tv/busca/walking%20dead%20s03e02")
html = browser.page_source
soup = BeautifulSoup(html, features="html.parser")
print(soup)
browser.quit()
Chrome 也是如此:
from bs4 import BeautifulSoup
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--headless')
# executable_path param is not needed if you updated PATH
browser = webdriver.Chrome(options=options, executable_path='YOUR_PATH/chromedriver.exe')
browser.get("http://legendas.tv/busca/walking%20dead%20s03e02")
html = browser.page_source
soup = BeautifulSoup(html, features="html.parser")
print(soup)
browser.quit()
最好记住browser.quit() 以避免在代码执行后挂起进程。如果您担心您的代码在浏览器被处理之前可能会失败,您可以将其包装在 try...except 块中并将 browser.quit() 放入 finally 部分以确保它会被调用。
此外,如果使用该方法仍未加载部分源代码,您可以要求 selenium 等待特定元素出现:
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
from selenium.common.exceptions import TimeoutException
options = webdriver.FirefoxOptions()
options.add_argument('--headless')
browser = webdriver.Firefox(options=options, executable_path='YOUR_PATH/geckodriver.exe')
try:
browser.get("http://legendas.tv/busca/walking%20dead%20s03e02")
timeout_in_seconds = 10
WebDriverWait(browser, timeout_in_seconds).until(ec.presence_of_element_located((By.ID, 'resultado_busca')))
html = browser.page_source
soup = BeautifulSoup(html, features="html.parser")
print(soup)
except TimeoutException:
print("I give up...")
finally:
browser.quit()
如果您对 Firefox 或 Chrome 以外的其他驱动程序感兴趣,请查看docs。