从链家网爬取指定城市的二手房信息,并将数据保存为CSV文件。它使用了Selenium库来模拟浏览器行为,以便获取动态加载的页面内容。具体而言,它实现了一个名为LianJia的类,其中包含了获取房源列表和房源详情的方法。主要步骤如下:
- 读取城市信息和代理IP信息,并初始化Chrome浏览器及其设置。
- 定义LianJia类,其中house_list()方法用于获取指定城区的所有房源链接,house_detail()方法用于获取单个房源的详细信息。
- run()方法用于执行爬取过程,它首先访问链家网站,然后获取指定城市的所有城区链接,再依次遍历每个城区,获取所有房源的详细信息,并保存到CSV文件中。
- 最后,循环遍历所有城市,调用run()方法执行爬取任务。
- 需要注意的是,这段代码在使用Selenium时需要确保已经安装好Chrome浏览器和对应版本的ChromeDriver,并将ChromeDriver的路径添加到系统环境变量中。
from selenium import webdriver
from fake_useragent import UserAgent
import random
from selenium.webdriver.common.by import By
import os
import pandas as pd
from pinyin import pinyin
import subprocess
# 读取城市信息
with open("city.txt", "r", encoding="utf-8") as file:
cities = [line.strip() for line in file if line.strip()]
ips = []
with open('ip.txt', 'r') as f:
for line in f:
ip = line.strip()
ips.append(ip.strip())
# 启动Chrome浏览器调试服务
subprocess.Popen('cmd', shell=True)
subprocess.Popen('chrome-win64\chrome.exe" --remote-debugging-port=9222', shell=True)
chrome_options

最低0.47元/天 解锁文章
3万+

被折叠的 条评论
为什么被折叠?



