【问题标题】:Javascript code not extracted with python codeJavascript代码不是用python代码提取的
【发布时间】:2019-09-16 20:16:50
【问题描述】:
我正在尝试从网站中提取 .mp4 链接,该链接仅显示在网络浏览器的“检查元素”选项卡中。
我在互联网上读到我需要使用 selenium,例如 PhantomJS 来获取该代码。我试过了,但我得到了在“显示源代码”中可见的 HTML 文件
from selenium import webdriver
driver = webdriver.PhantomJS(executable_path=r'C:\Users\Nevendary\Desktop\phantomjs-2.1.1-windows\bin\phantomjs')
driver.get("https://filmovitica.com/pucanj-u-sljiviku-preko-reke-1978-domaci-film-gledaj-online/")
driver.implicitly_wait(30)
print(driver.page_source)
我希望得到的代码包括:https://fs40.gounlimited.to/tea5u5akd32qzxfffpqyfndb6resauu5w43w7enoxkvu6sjtrf5hfhbz3ika/v.mp4"
但我得到的只是网站的普通 HTML
【问题讨论】:
标签:
javascript
python
html
selenium
phantomjs
【解决方案1】:
您可以直接获取视频元素的src 属性,而不是搜索页面源,其中包含您要查找的链接。
视频链接位于iframe。在不切换到框架的情况下获取页面源不会返回视频链接。
我已经使用 chromedriver 进行示例。
试试这个:
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(executable_path="chromedriver.exe")
wait = WebDriverWait(driver, 20)
driver.get("https://filmovitica.com/pucanj-u-sljiviku-preko-reke-1978-domaci-film-gledaj-online/")
vframe = driver.find_element_by_xpath("//iframe[@width='900']")
driver.switch_to.frame(vframe)
videoElement = wait.until(EC.visibility_of(driver.find_element(By.CSS_SELECTOR, "#vplayer > div > div.container > video")))
print(videoElement.get_attribute('src'))
driver.quit()
【解决方案2】:
尝试将ChromeDriver 与headless 选项一起使用,而不是PhantomJS。这会给我你想要的输出。
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
driver=webdriver.Chrome(executable_path='path of chrome driver',options=chrome_options)
driver.get("https://filmovitica.com/pucanj-u-sljiviku-preko-reke-1978-domaci-film-gledaj-online/")
print(driver.page_source)
注意:如果您没有安装 chromedriver,请根据您的浏览器兼容性从以下链接下载 chromedriver。请在下载任何 chrome 驱动程序之前阅读发行说明以确保兼容性。 Download Chrome driver
使用 Python 库 Beautiful Soup 的另一种方法。
import requests
from bs4 import BeautifulSoup
data=requests.get('https://filmovitica.com/pucanj-u-sljiviku-preko-reke-1978-domaci-film-gledaj-online/')
soup=BeautifulSoup(data.text,'html.parser')
print(soup)
注意:安装很容易pip install beautifulsoup4你可以查看以下关于美丽汤的链接Beautiful Soup
【解决方案3】:
检查 html 确实似乎链接是在 iframe 使用的相同 url 内生成的。您可以使用 requests 来获取:
import requests
from bs4 import BeautifulSoup
res = requests.get('https://filmovitica.com/pucanj-u-sljiviku-preko-reke-1978-domaci-film-gledaj-online/')
soup = bs(res.content, 'lxml')
print(soup.select_one('iframe[allowfullscreen]')['src'])
您可以在 uri 中的一个脚本标签中找到它(您的字符串)是如何生成的(请参阅开头以蓝色突出显示的行:
稍后在那个js中: