Selenium无法加载可见<p>标签,如何实现页面完整渲染?
解决Selenium无法完整渲染页面获取
标签的问题
针对你遇到的页面渲染不完整、
标签缺失的问题,可以从以下几个方向调整脚本,确保页面内容完全加载:
1. 替换固定等待为显式等待
固定的time.sleep(10)无法精准判断页面加载状态,改用Selenium的显式等待,等待页面完全就绪或目标元素出现,避免提前获取未渲染完成的页面源码。
2. 模拟滚动触发动态加载
部分新闻网站会通过滚动加载后续内容,需要执行JavaScript模拟滚动到底部,触发动态内容渲染。
3. 修正文本匹配逻辑
BeautifulSoup的精确文本匹配(text='Live Updates:')容易因标签内的空格、换行等不可见字符失效,改用正则表达式做模糊匹配更可靠。
4. 添加浏览器防爬配置
设置真实的User-Agent模拟普通浏览器请求,同时处理可能存在的Cookie弹窗,避免弹窗干扰页面加载。
修改后的完整代码
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 import re def get_webpage(): chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--no-sandbox") # chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument('--disable-dev-shm-usage') # 模拟真实浏览器的User-Agent chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36") driver = webdriver.Chrome(options=chrome_options) url = 'https://www.israelnationalnews.com/news/378955' driver.get(url) try: # 等待页面DOM加载完成 WebDriverWait(driver, 20).until( lambda driver: driver.execute_script('return document.readyState') == 'complete' ) # 滚动到页面底部,触发动态内容加载 driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # 等待滚动后内容加载完成 WebDriverWait(driver, 10).until( lambda driver: driver.execute_script('return document.body.scrollHeight') == driver.execute_script('return window.innerHeight + window.scrollY') ) # 处理Cookie弹窗(如果存在) try: accept_btn = WebDriverWait(driver, 5).until( EC.element_to_be_clickable((By.CSS_SELECTOR, "button[aria-label='Accept cookies']")) ) accept_btn.click() except: # 无弹窗则跳过 pass webpage_content = driver.page_source finally: driver.quit() # 解析页面内容 soup = BeautifulSoup(webpage_content, 'html.parser') # 用正则匹配包含"Live Updates:"的<p>标签 target_p_tag = soup.find('p', text=re.compile(r'Live Updates:')) if target_p_tag: next_p_tag = target_p_tag.find_next('p') if next_p_tag: extracted_text = next_p_tag.get_text(strip=True) print(extracted_text) else: print("No next <p> tag found.") else: print("No <p> tag containing 'Live Updates:' found.") if __name__ == "__main__": get_webpage()
内容的提问来源于stack exchange,提问作者Imcha Anochi
相关产品推荐
相关产品推荐

