Python网页爬取循环问题:遍历URL集时循环提前终止
问题分析与修复方案
核心问题
循环只处理第一个URL就停止,根源是你在处理第一个页面时就调用了driver.quit(),直接关闭了Chrome驱动,后续循环没有可用的浏览器实例,自然无法继续执行。另外,代码里的NoSuchElementException捕获完全无效——这个异常是Selenium原生查找元素时才会抛出的,而你用的是BeautifulSoup解析页面,不会触发该异常。
修复步骤
- 移除循环内的
driver.quit():将浏览器关闭操作移到整个URL遍历循环结束之后,确保所有页面处理完成再关闭驱动。 - 调整页面处理逻辑:不要在找到第一个符合条件的元素就终止,而是遍历当前页面所有符合要求的元素,处理完当前页面再进入下一个URL的循环。
- 修正元素存在判断:通过检查BeautifulSoup返回的列表是否为空,来判断目标元素是否存在,替代无效的异常捕获。
修正后的代码
from cgitb import text import re from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from bs4 import BeautifulSoup from time import sleep from random import randint chromedriver_path = "C:\Program Files (x86)\chromedriver.exe" service = Service(chromedriver_path) options = Options() # options.headless = True options.add_argument("--incognito") driver = webdriver.Chrome(service=service, options=options) ## Variables url = 'https://hackerone.com/bug-bounty-programs' base_url = 'https://' bountydomains = set() ## Initial Scrape ## Sleep to load ## find all ul > li tags by class ## Add base url and export as set driver.get(url) print('SCRAPING HACKERONE') sleep(randint(10,12)) driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") soup = BeautifulSoup(driver.page_source,'html.parser') for ultag in soup.find_all('ul', {'class': 'program__meta-data list--inline'}): for link in ultag.find_all('li', {'class': ''}): bountydomains.add(base_url+link.text) ## WORKING ## Scrape based of url list ## Only finds ul > daisylist > li - text for link in bountydomains: driver.get(link) print('Currently Scraping: ' + link) sleep(randint(10,12)) driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") soup = BeautifulSoup(driver.page_source,'html.parser') # 查找目标ul元素 target_uls = soup.find_all('ul', {'class': 'daisy-list'}) if not target_uls: print('Element not found for link:' + link) continue # 遍历所有符合条件的li元素 found_valid = False for ultags in target_uls: for links in ultags.find_all('li', {'class': ''}): if ".com" in links.text or ".id" in links.text: print("URL found:" + links.text) found_valid = True if not found_valid: print('No matching text found for url:' + link ) # 所有URL处理完成后再关闭浏览器 driver.quit() exit()
关键修改说明
- 把
driver.quit()移到了整个for link in bountydomains循环的外面,确保所有页面都处理完再关闭浏览器。 - 用
target_uls = soup.find_all('ul', {'class': 'daisy-list'})获取目标元素列表,通过if not target_uls判断元素是否存在,替代原来无效的异常捕获。 - 增加
found_valid标记,遍历当前页面所有li元素,找到所有符合.com或.id的内容后,再统一判断是否有有效内容,避免中途终止处理。
内容的提问来源于stack exchange,提问作者lukesudom
相关产品推荐
相关产品推荐

