【问题标题】:Selenium and BeautifulSoup can't fetch all HTML contentSelenium 和 BeautifulSoup 无法获取所有 HTML 内容
【发布时间】:2020-06-29 16:54:31
【问题描述】:

我正在删除https://lngconnection.cheniere.com/#/ccpl 上标有“容量:可操作 - 晚上”的底部表格

当我 prettify() 打印 HTML 时,我能够获取所有 HTML 并且所有内容都显示出来,但是当我发出命令以查找我需要的特定信息时,解析器找不到它。

这是我的脚本:

cc_driver = webdriver.Chrome('/Users/.../Desktop/chromedriver')
cc_driver.get('https://lngconnection.cheniere.com/#/ccpl')
cc_html = cc_driver.page_source

cc_content = soup(cc_html, 'html.parser')
cc_driver.close()
cc_table = cc_content.find('table', class_='k-selectable')
#print(cc_content.prettify())
print(cc_table.prettify())

现在我做的时候

print(cc_table.prettify())

输出是除实际表数据之外的所有内容。我的代码或它们的 HTML 中是否存在隐藏实际表值的错误?当我打印 Selenium 在页面上捕获的所有内容时,我能够看到它。 HTML 也没有任何单元格值的特定 ID 标记。

【问题讨论】:

    标签: python html selenium web-scraping beautifulsoup


    【解决方案1】:

    您正在查看尚未完成的 HTML。所有元素尚未从 javascript 返回。所以你可以做一个 webdriver 等待。

    from selenium import webdriver
    from bs4 import BeautifulSoup as soup
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    cc_driver = webdriver.Chrome(r"path for driver")
    cc_driver.get('https://lngconnection.cheniere.com/#/ccpl')
    WebDriverWait(cc_driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, 
    '#capacityGrid > table > tbody')))
    cc_html = cc_driver.page_source
    
    cc_content = soup(cc_html, 'html.parser')
    cc_driver.close()
    cc_table = cc_content.find('table', class_='k-selectable')
    #print(cc_content.prettify())
    print(cc_table.prettify())
    

    这将等待元素出现。

    【讨论】:

    • 非常感谢。这行得通,我不知道添加等待。我不得不通过 XPATH 而不是 CSS_SELECTOR 找到,但它是一回事,谢谢 Mohammed 兄弟
    【解决方案2】:

    这应该可以帮助您获取表格 html

    from selenium import webdriver
    from bs4 import BeautifulSoup as bs
    
    cc_driver = webdriver.Chrome('../chromedriver_win32/chromedriver.exe')
    cc_driver.get('https://lngconnection.cheniere.com/#/ccpl')
    cc_html = cc_driver.page_source
    
    cc_content = bs(cc_html, 'html.parser')
    cc_driver.close()
    cc_table = cc_content.find('table', attrs={'class':'k-selectable'})
    
    #print(cc_content.prettify())
    print(cc_table.prettify())
    

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 2010-12-17
      • 2016-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多