如何从Selenium爬取的网页数据中移除header和footer区域
解决方法
你需要在提取文本前,先从BeautifulSoup解析的DOM结构中定位并移除header、footer节点,再提取剩余内容的文本即可。
大部分规范开发的网页会使用语义化的<header>标签包裹页头、<footer>标签包裹页脚,直接匹配标签删除即可;如果目标站点没有用语义化标签,可通过浏览器F12开发者工具查看对应区域的class、id属性,调整选择器定位即可。
修改后完整代码
from bs4 import BeautifulSoup import requests from selenium import webdriver from selenium.common.exceptions import WebDriverException from selenium.webdriver.chrome.service import Service options = webdriver.ChromeOptions() options.add_argument("--headless") service = Service("/home/ubuntu/selenium_drivers/chromedriver") URL = "https://www.uh.edu/kgmca/music/events/calendar/?view=e&id=30723#event" try: driver = webdriver.Chrome(service = service, options = options) driver.get(URL) driver.implicitly_wait(2) html_content = driver.page_source driver.quit() except WebDriverException: driver.quit() soup = BeautifulSoup(html_content, 'lxml') # 加上解析器避免运行警告 # 移除所有header节点 for header in soup.find_all('header'): header.decompose() # 移除所有footer节点 for footer in soup.find_all('footer'): footer.decompose() # 若目标区域不是语义化标签,可按class/id定位,示例: # for header in soup.find_all(class_='site-header'): # header.decompose() # for footer in soup.find_all(id='page-footer'): # footer.decompose() text = soup.getText(separator=' ')
说明
decompose()方法会将匹配到的节点从整个soup树中彻底移除,后续提取文本时不会再包含对应区域的内容- 用
find_all遍历匹配而不是find,可以避免页面存在多个同类型节点的情况 - 给BeautifulSoup加上
lxml解析器参数,可避免默认解析器的警告提示,运行效率也更高
内容的提问来源于stack exchange,提问作者imhans33
相关产品推荐
相关产品推荐

