selenium爬取某生活分类网站点击事件后弹出的信息

本文介绍如何利用Selenium WebDriver实现自动化登录58同城网站,并执行后续操作如申请职位等。通过Python代码演示了设置浏览器、加载网页、输入账号密码、点击登录、保存和读取cookies的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from selenium import webdriver
import pickle


url='https://bj.58.com/zhuanye/37291869116169x.shtml?'
base_url='https://passport.58.com/login/'

browser=webdriver.Firefox()
browser.get(base_url)
browser.implicitly_wait(10)

#切换密码登录
submit1=browser.find_element_by_class_name('pwdlogin')
browser.execute_script("arguments[0].click();", submit1)
browser.implicitly_wait(20)

#切换到账号密码登录方式

#输入账号
submit2=browser.find_element_by_id('usernameUser').send_keys('******')
browser.implicitly_wait(20)

#输入密码
js = 'document.getElementById("passwordUser").style.display="block";'
browser.execute_script(js)
browser.implicitly_wait(20)
submit3=browser.find_element_by_id('passwordUser').send_keys('*******')
browser.implicitly_wait(20)

#点击登录
submit =browser.find_element_by_class_name('submit')
browser.execute_script("arguments[0].click();", submit)
browser.implicitly_wait(10)
#验证登录是否成功
try:
    browser.find_element_by_class_name('uc-uname')
except:
    print('登录失败')
#保存cookies
pickle.dump(browser.get_cookies(),open("cookies.pkl", "wb"))

#刷新浏览器
browser.refresh()
browser.implicitly_wait(20)

#读取cookies流
cookies = pickle.load(open("cookies.pkl", "rb"))
#构造cookies
for cookie in cookies:
    cookie_dict = {
      # domain火狐浏览器不用填写,谷歌要需要
     'name': cookie.get('name'),
     'value': cookie.get('value'),
     "expires": "",
     'path': '/',
     'httpOnly': False,
     'HostOnly': False,
     'Secure': False}
     #添加cookies
    browser.add_cookie(cookie_dict)

browser.implicitly_wait(20)
#登录目标页面
browser.get(url)#browser.implicitly_wait(20)
browser.implicitly_wait(20)
#点击申请
submit11 =browser.find_element_by_class_name('btn.btn-orange.btn-large.applyJobBtn')
browser.execute_script("arguments[0].click();", submit11)

#弹出的指示框架,选择‘关闭’
submit12 = browser.find_element_by_id('close-guide')
browser.execute_script("arguments[0].click();", submit12)

browser.implicitly_wait(3)
submit13 = browser.find_element_by_class_name('pos_operate_item.showPhoneBtn')
browser.execute_script("arguments[0].click();", submit13)

teacher_tel=browser.find_element_by_xpath('//div[@class="tan"]/p').get_attribute('textContent')
print(teacher_tel)

 

<think>我们正在使用Java和Selenium爬取图片,并需要在点击下载按钮后获取文件名。根据引用[2]:Selenium无法直接操作文件上传/下载窗口,因为这些窗口是系统级的控件。但是,对于下载操作,我们通常可以通过设置浏览器的下载选项来避免弹出下载窗口,从而直接获取文件名或等待文件下载完成。思路:1.在开始下载之前,设置浏览器(例如Chrome)的下载选项,将默认下载目录设置为一个已知路径,并禁止下载弹出窗口(即不询问下载位置)。2.点击下载按钮。3.等待文件下载完成(通过检查下载目录中是否有新文件出现)。4.获取下载目录中的最新文件(或匹配文件)的文件名。但是,注意:我们无法在文件下载过程中(或下载完成前)通过Selenium直接获取到文件名,因为文件名是在下载响应头中确定的。因此,我们需要等待文件下载到本地目录,然后从目录中读取文件名。步骤:1.配置浏览器下载选项。2.执行点击下载按钮的操作。3.等待文件出现在下载目录中。4.获取文件名。参考引用[4]中的方法,我们可以判断指定文件夹下是否存在下载的文件,并获取文件名。具体实现:首先,我们需要配置Chrome浏览器的下载选项。以下是一个配置示例:```javaimportorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeDriver;importorg.openqa.selenium.chrome.ChromeOptions;importjava.util.HashMap;importjava.util.Map;publicclassDownloadFileExample{publicstaticvoidmain(String[]args){//设置ChromeDriver路径System.setProperty("webdriver.chrome.driver","E:\\chromedriver\\chromedriver.exe");//创建Chrome选项ChromeOptionsoptions=newChromeOptions();//设置下载路径(这里设置为当前项目目录下的downloads文件夹)StringdownloadPath=System.getProperty("user.dir")+"\\downloads";Map<String,Object>prefs=newHashMap<>();prefs.put("download.default_directory",downloadPath);prefs.put("download.prompt_for_download",false);//禁止弹出下载窗口prefs.put("download.directory_upgrade",true);prefs.put("safebrowsing.enabled",true);//安全浏览,可以禁用options.setExperimentalOption("prefs",prefs);//创建WebDriverWebDriverdriver=newChromeDriver(options);//访问页面driver.get("目标网页URL");//定位下载按钮并点击//driver.findElement(...).click();//等待文件下载完成(这里需要根据实际情况等待一段时间,或者轮询目录直到文件出现)//我们可以使用引用[4]中的方法判断文件是否下载完成//例如,等待10秒(实际可能需要根据文件大小调整)Thread.sleep(10000);//获取下载目录中的最新文件Filedir=newFile(downloadPath);File[]files=dir.listFiles();if(files!=null&&files.length>0){//假设我们按最后修改时间排序,获取最新的文件Arrays.sort(files,(f1,f2)->Long.compare(f2.lastModified(),f1.lastModified()));FilelastFile=files[0];StringfileName=lastFile.getName();System.out.println("下载的文件名:"+fileName);}//关闭浏览器driver.quit();}}```注意:上述代码中,我们设置了下载目录,并且禁止了下载提示,这样点击下载按钮后文件会自动下载到指定目录。但是,等待文件下载完成的方式可能不够健壮(使用固定等待时间)。更好的做法是轮询下载目录,直到出现一个与预期匹配的文件(例如,扩展名为.jpg、.png等)并且文件大小稳定(即下载完成)。改进的等待方法(参考引用[4]中的思路):```javaprivatestaticStringgetDownloadedFileName(StringdownloadPath,StringfileExtension)throwsInterruptedException{Filedir=newFile(downloadPath);File[]files;longstartTime=System.currentTimeMillis();longwaitTime=30000;//最多等待30秒while(System.currentTimeMillis()-startTime<waitTime){files=dir.listFiles();if(files!=null){//查找扩展名匹配的文件for(Filefile:files){if(file.getName().endsWith(fileExtension)){//检查文件是否正在下载(部分浏览器下载时会有临时扩展名,如.crdownload)if(!file.getName().contains(".crdownload")){returnfile.getName();}}}}Thread.sleep(1000);//每秒检查一次}returnnull;//超时未找到}```注意:不同浏览器下载过程中可能会有临时文件(Chrome会创建.crdownload文件),因此我们需要忽略这些临时文件,只返回没有临时扩展名的文件。因此,在点击下载按钮后,我们可以调用这个方法:```javaStringfileName=getDownloadedFileName(downloadPath,".jpg");//假设下载的是jpg图片if(fileName!=null){System.out.println("下载的文件名:"+fileName);}else{System.out.println("下载失败或超时");}```总结:1.配置浏览器自动下载到指定目录。2.点击下载按钮。3.轮询下载目录,直到找到目标文件(注意排除临时文件)。4.获取文件名。注意:如果下载的文件名是动态的(每次下载文件名不同),我们只能通过这种方式获取。如果文件名是固定的,那么我们可以直接检查该文件是否存在。另外,如果下载按钮触发的下载链接中包含了文件名,我们也可以通过解析该链接来获取文件名(但可能不是最终的文件名,因为服务器可能重定向或修改文件名)。因此,从下载目录获取是最直接的方式。根据引用[3]和[5],Selenium可以用于获取动态加载的内容,因此我们也可以尝试获取下载链接的元素属性(例如href)来解析文件名,但这不适用于通过JavaScript触发的下载。所以,从下载目录获取文件名是更通用的方法。请根据实际情况调整代码。</think>### Java Selenium 获取下载文件名的方法 要使用 Java Selenium 在点击下载按钮后获取文件名,核心思路是通过监控下载目录并检测新出现的文件。以下是完整解决方案: ```java import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import java.io.File; import java.util.*; import java.util.concurrent.TimeUnit; public class ImageDownloader { // 配置浏览器下载参数 private static void setDownloadPreferences(ChromeOptions options, String downloadPath) { Map<String, Object> prefs = new HashMap<>(); prefs.put("download.default_directory", downloadPath); prefs.put("download.prompt_for_download", false); // 禁止弹出下载窗口 prefs.put("download.directory_upgrade", true); prefs.put("safebrowsing.enabled", false); // 禁用安全浏览警告 options.setExperimentalOption("prefs", prefs); } // 获取下载目录中的最新文件名 private static String getLatestFileName(String downloadPath) { File dir = new File(downloadPath); File[] files = dir.listFiles(); if (files == null || files.length == 0) return null; // 按修改时间排序获取最新文件 return Arrays.stream(files) .filter(File::isFile) .max(Comparator.comparingLong(File::lastModified)) .map(File::getName) .orElse(null); } public static void main(String[] args) { // 配置下载路径 String downloadPath = "C:\\Users\\yourname\\Downloads\\selenium_downloads"; new File(downloadPath).mkdirs(); // 确保目录存在 // 浏览器设置 System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe"); ChromeOptions options = new ChromeOptions(); setDownloadPreferences(options, downloadPath); WebDriver driver = new ChromeDriver(options); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); try { // 访问目标页面 driver.get("https://example.com/image-gallery"); // 获取所有图片下载按钮(根据实际页面调整选择器) List<WebElement> downloadButtons = driver.findElements( By.cssSelector("button.download-btn") ); for (WebElement button : downloadButtons) { // 记录点击前的文件列表 Set<String> beforeFiles = new HashSet<>( Arrays.asList(new File(downloadPath).list()) ); // 点击下载按钮 button.click(); // 等待文件出现(最大等待10秒) String newFileName = null; for (int i = 0; i < 10; i++) { Set<String> afterFiles = new HashSet<>( Arrays.asList(new File(downloadPath).list()) ); afterFiles.removeAll(beforeFiles); if (!afterFiles.isEmpty()) { newFileName = afterFiles.iterator().next(); break; } Thread.sleep(1000); // 每秒检查一次 } if (newFileName != null) { System.out.println("下载成功: " + newFileName); // 这里可添加图片处理逻辑 } else { System.out.println("下载失败: 超时未检测到文件"); } } } catch (Exception e) { e.printStackTrace(); } finally { driver.quit(); } } } ``` ### 关键实现原理 1. **浏览器配置** - 使用 `ChromeOptions` 设置默认下载目录 - 禁用下载确认弹窗 (`download.prompt_for_download=false`) - 关闭安全浏览警告提高下载速度 2. **文件名检测机制** - 点击前记录目录文件快照 - 点击后轮询目录检测新增文件 - 通过文件修改时间戳确认最新文件 - 设置超时机制防止无限等待 3. **异常处理** - 自动创建下载目录确保路径有效 - 捕获可能的超时和文件访问异常 - 确保浏览器进程最终关闭 ### 注意事项 1. **文件类型过滤** ```java // 在检测文件时添加类型过滤 afterFiles.removeIf(file -> !file.endsWith(".jpg") && !file.endsWith(".png")); ``` 2. **临时文件处理** - Chrome 下载时会先创建 `.crdownload` 临时文件 - 添加等待逻辑直到临时文件消失: ```java while (newFileName.endsWith(".crdownload")) { Thread.sleep(500); newFileName = getLatestFileName(downloadPath); } ``` 3. **动态文件名问题** - 如果文件名含时间戳/随机数,可通过模式匹配: ```java Pattern pattern = Pattern.compile("image_\\d{8}\\.jpg"); if (pattern.matcher(newFileName).matches()) { // 有效文件名 } ``` ### 优化建议 1. **使用明确等待** ```java new WebDriverWait(driver, 10) .until(d -> new File(downloadPath).list().length > initialCount); ``` 2. **文件完整性验证** ```java File file = new File(downloadPath + File.separator + newFileName); long lastSize; do { lastSize = file.length(); Thread.sleep(1000); } while (file.length() > lastSize); // 直到文件不再增长 ``` 3. **多线程下载管理** - 使用 `ExecutorService` 管理并行下载 - 为每个下载任务创建独立子目录 此方案通过监控文件系统变化获取下载文件名,避免了Selenium无法直接操作下载窗口的限制[^2],同时确保代码健壮性和可扩展性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值