引言
本次爬虫使用了selenium,结合Chrome浏览器进行信息爬取,在数据存储方面,用了MongoDB数据库。
特别声明
代码仅供交流学习,不要用来做违法的事情。
思路分析
起始URL:'https://www.fang.com/SoufunFamily.htm
通过此URL,我们可以获取到全国各大城市的URL,然后,通过获取到的城市URL进行URL拼接,就可以得到每个城市新房页面的URL。由于每个页面还有下一页,可以用XPath定位到下一页的按钮,然后模拟点击就可以来到下一个页面了,再继续提取这个页面的信息即可。重复上述步骤,就可以完成新房信息的爬取。具体代码如下:
完整代码
# !/usr/bin/env python
# —*— coding: utf-8 —*—
# @Time: 2020/2/6 21:00
# @Author: Martin
# @File: 房天下.py
# @Software:PyCharm
import requests
import re
import time
import pymongo
from lxml import etree
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
class FangSpider(object):
def __init__(self):
self.driver = webdriver.Chrome(executable_path='./chromedriver.exe')
self.start_url = 'https://www.fang.com/SoufunFamily.htm'
self.client = pymongo.MongoClient(host="localhost", port=27017)
self.db = self.client['fangtianxia']
def run(self):
self.driver.get(self.start_url)
WebDriverWait(driver=self.driver, timeout=10).until(
EC.presence_of_element_located((By.XPATH, '//table[@class="table01"]/tbody/tr'))
)
source

本文介绍了使用selenium和Chrome浏览器爬取房天下新房信息的过程。通过起始URL获取全国城市新房页面,利用XPath定位下一页并提取信息,存储到MongoDB数据库。虽然效率较低,但在无数据接口或页面有js混淆时,selenium提供了解决方案。
最低0.47元/天 解锁文章
1160

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



