使用Java语言和selenium爬取58同城二手房中,石河子地区首页的二手房信息,在第一页的信息中,将小区地址、房屋面积、房屋总价3个信息打印出来的代码
时间: 2024-06-09 09:04:32 浏览: 12
以下是使用Java语言和Selenium爬取58同城二手房石河子地区首页的二手房信息,并将小区地址、房屋面积、房屋总价3个信息打印出来的示例代码:
```java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) {
// 设置Chrome浏览器驱动路径
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
// 创建Chrome浏览器驱动对象
WebDriver driver = new ChromeDriver();
// 访问58同城二手房石河子地区首页
driver.get("https://shz.58.com/ershoufang/");
// 获取页面上所有的二手房信息元素
java.util.List<WebElement> houseList = driver.findElements(By.xpath("//ul[@class='house-list-wrap']/li"));
// 遍历每个二手房信息元素
for (WebElement house : houseList) {
// 获取小区地址元素
WebElement addressElement = house.findElement(By.xpath(".//a[@class='property-address']/span"));
String address = addressElement.getText(); // 获取小区地址文本
// 获取房屋面积元素
WebElement areaElement = house.findElement(By.xpath(".//div[@class='property-area']/span[@class='area']/b"));
String area = areaElement.getText(); // 获取房屋面积文本
// 获取房屋总价元素
WebElement priceElement = house.findElement(By.xpath(".//div[@class='property-price']/span[@class='total']/b"));
String price = priceElement.getText(); // 获取房屋总价文本
// 打印小区地址、房屋面积、房屋总价信息
System.out.println("小区地址:" + address);
System.out.println("房屋面积:" + area);
System.out.println("房屋总价:" + price);
}
// 关闭浏览器驱动对象
driver.quit();
}
}
```
需要注意的是,示例代码中的Chrome浏览器驱动路径需要根据本地的实际情况进行修改。另外,需要在项目中引入Selenium相关依赖,如下所示:
```xml
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>3.141.59</version>
</dependency>
</dependencies>
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)