【问题标题】:Selenium Python Empty return after page update页面更新后 Selenium Python Empty 返回
【发布时间】:2020-08-23 17:38:19
【问题描述】:

我正在使用 Selenium Python 和 BeautifulSoup 来抓取数据。 单击“实时”按钮后,我需要网站的 html。我正在单击要单击的按钮,但是没有将新的 HTML 返回给我。 我认为单击按钮后 html 会很快返回,所以我睡了。但即便如此,它也只返回“Collapsible__contentInner”类的空 div。

from bs4 import BeautifulSoup
from selenium import webdriver

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = 'https://www.365scores.com/pt-br/football'

web_r = requests.get(url)
web_soup = BeautifulSoup(web_r.text, 'html.parser')

driver = webdriver.Firefox()
driver.get(url)

botaoPopUp = WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div/div[1]/div[3]/div/div[2]/div[1]/div[2]/button')))
botaoPopUp.click()

elemento = driver.find_element_by_xpath('/html/body/div[2]/div/div[1]/div[3]/div/div[2]/div/div[2]/div/div/div[1]/div/div[1]/div/div[1]')
elemento.click()

import time 
time.sleep(10)

html = driver.page_source
soup = BeautifulSoup(html, 'lxml')
dados = soup.find('div', class_="Collapsible__contentInner")
print(dados)

结果

<div class="Collapsible__contentInner"><div style="position: relative;"></div></div>

【问题讨论】:

    标签: javascript python selenium scrape


    【解决方案1】:

    不要使用 page_source。

    使用网络驱动直接访问元素:

    driver.find_element_by_css_selector('.Collapsible__contentInner')

    然后您可以访问该元素的内容或属性,请参阅 selenium 码头。

    【讨论】:

      【解决方案2】:

      首先获取页面的所有HTML源,然后抓取一些元素属性不是一个非常明智的想法。尽管如此,如果您想使用 page_source 获取页面的 HTML 源代码,这并不是一个非常可靠的想法,因为它不能保证它会返回页面 HTML 源代码的当前状态。而是使用 JavaScript outerHTML,如下所示:

      html = driver.execute_script("return document.documentElement.outerHTML")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-19
        • 1970-01-01
        • 2016-07-10
        • 2015-06-10
        相关资源
        最近更新 更多