public static void main(String[] args){ System.setProperty("webdriver.firefox.bin","C:\Users\Y\Desktop\软件测试\实验二\实验相关\FirefoxChina_13.0.1\Mozilla Firefox\firefox.exe"); WebDriver driver = new FirefoxDriver(); Navigation na = driver.navigate(); na.to("https://shz.58.com/ershoufang/"); driver.findElement(By.id("search-input")).clear(); List<WebElement> ele = driver.findElements(By.cssSelector("h3.property-content-title-name"));//爬取房屋名字 List<WebElement> ele1s=new ArrayList<>(); List<WebElement> ele3s=new ArrayList<>(); for(int j=1;j<=10;j++){ String s1="//div[@id='__layout']/div/section/section[3]/section/section[2]/div["+j+ "]/a/div[2]/div/section/div[@class='property-content-info']/p[2]"; String s3="//div[@id='__layout']/div/section/section[3]/section/section[2]/div["+j+ "]/a/div[2]/div/section/div[@class='property-content-info property-content-info-comm']/p[2]"; WebElement ele11 = driver.findElement(By.xpath(s1));//爬取房屋面积信息 WebElement ele33 = driver.findElement(By.xpath(s3));//爬取房屋地址信息 ele1s.add(ele11); ele3s.add(ele33); } List<WebElement> ele2 = driver.findElements(By.cssSelector("p.property-price-total"));//爬取房屋价格信息 for(int i=0;i<ele1s.size();i++){ System.out.println("名字:"+ele.get(i).getText()); System.out.println("地址:"+ele3s.get(i).getText()); System.out.println("面积:"+ele1s.get(i).getText()); System.out.println("价格:"+ele2.get(i).getText()); System.out.println(); } }
时间: 2023-06-18 16:06:12 浏览: 192
这是一个 Java 程序,主要是使用 Selenium WebDriver 来爬取 58 同城二手房的房屋信息。程序的主要流程是:
1. 设置 Firefox 浏览器的路径;
2. 创建 FirefoxDriver 对象;
3. 使用 navigate() 方法访问 58 同城二手房的页面;
4. 清空搜索框中的内容;
5. 使用 findElements() 方法找到所有的房屋名称、面积、地址和价格信息;
6. 使用 for 循环遍历每个房屋的信息,并打印出来。
需要注意的是,程序中使用了多个 XPath 表达式来定位元素,这些表达式需要根据实际页面结构进行修改。另外,程序中只爬取了页面上的前 10 个房屋信息,如果需要爬取更多的信息,需要修改 for 循环的终止条件。
阅读全文
相关推荐



