python使用代理爬取安居客二手房数据(一)

一、背景

主要是想爬取湖北省武汉市江汉区的二手房数据:“title”, “house_type”, “area”, “decoration”, “price”,为了防止ip被封,用了kuaidaili进行爬取。

二、实战

鼠标放在标题上右键点击检查
查看其它内容同上
在这里插入图片描述
点击第二页出现右图
在这里插入图片描述
这样就得到了头部headers,放在请求项里去访问网址
在这里插入图片描述

import pandas as pd
import requests
from bs4 import BeautifulSoup
import random


# 构造url的request headers,伪装成正常用户
headers = {
    'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cache-control': 'no-cache',
    'cookie': 'aQQ_ajkguid=70C0288A-42CB-4C56-B8EF-8E90F8077A8C; sessid=13C76F04-9178-4EE8-B8B0-F00FE21F4F50; ajk-appVersion=; ctid=22; fzq_h=d23302afd92c82b304657a734e3950aa_1697613588983_b645e9292cff4c148c0e3fb2ff31662e_3746354997; id58=CrIej2Uvhxc/D8k8IRI2Ag==; twe=2; fzq_js_anjuke_ershoufang_pc=8e86fa86290dbac07d5de51dd3b9db13_1697615100824_23; obtain_by=1; xxzl_cid=817f908b661647889fa49debaab80d9c; xxzl_deviceid=lrdQ4FRXrfXyN2Qj/gRhBw2SQpTZ81igKeOBCkzlfzjPwEG8whpE1uKNvVqIOvXQ',
    'host': 'wuhan.anjuke.com',
    'pragma': 'no-cache',
    'referer': 'https://wuhan.anjuke.com/sale/jianghana/p1/',
    'sec-ch-ua': '"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': "Windows",
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36'
}


# 构造url
craw_url = "https://wuhan.anjuke.com/sale/{region}/p{page}/"
region = "jianghana"


# 配置API接口信息

# API接口,返回格式为json
api_url = ""  # 替换成自己的


# API接口返回的ip
proxy_ip = requests.get(api_url).json()['data']['proxy_list']
print(proxy_ip)

# 用户名密码认证(私密代理/独享代理)
username = ""  # 替换成自己的
password = ""  # 替换成自己的

proxies = {
    "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {'user': username, 'pwd': password, 'proxy': random.choice(proxy_ip)},
    "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {'user': username, 'pwd': password, 'proxy': random.choice(proxy_ip)}
}



# 创建一个空DataFrame,用于存储数据
house_df = pd.DataFrame(columns=["title", "house_type", "area", "decoration", "price"])

# 循环抓取不同页码的数据(这里只爬取了99页内容)
for page in range(1, 100):
    print("开始爬取第 %s 页" % page)
    url = craw_url.format(region=region, page=page)
    response = requests.get(url,  headers=headers, proxies=proxies, timeout=5)
    html = response.text
    soup = BeautifulSoup(html, "html.parser")
    # print(soup)
    house_list = soup.find_all('div', class_='property-content')
    # print(house_list)

    # 解析房源信息
    for house in house_list:
        # 解析基本信息
        title = house.find("h3", class_="property-content-title-name").text.strip()
        #house_type = house.find_all("p")[0].text.strip()
        house_data = house.find('p', class_='property-content-info-text property-content-info-attribute')
        layout_datas = house_data.find_all('span')
        datas_shi = layout_datas[0].get_text() + layout_datas[1].get_text()
        datas_ting = layout_datas[2].get_text() + layout_datas[3].get_text()
        datas_wei = layout_datas[4].get_text() + layout_datas[5].get_text()
        house_type = datas_shi+datas_ting+datas_wei
        area = house.find_all("p")[1].text.strip()
        decoration = house.find_all("p")[2].text.strip()

        # 解析价格信息
        price_tag = house.find("div", class_="property-price")
        price = price_tag.find("span", class_='property-price-total-num').text.strip() if price_tag else "未知"

        # 将数据存入DataFrame
        house_df.loc[len(house_df)] = [title, house_type, area, decoration, price]

        # 输出数据到CSV
house_df.to_csv("house.csv", index=False, encoding="utf_8_sig")

最后结果
在这里插入图片描述

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,以下是爬取安居客二手房数据的代码: 首先,在命令行中使用`scrapy startproject anjuke`创建一个新的项目。 在`anjuke/spiders`目录下创建`anjuke_spider.py`文件,写入以下代码: ```python import scrapy class AnjukeSpider(scrapy.Spider): name = "anjuke" start_urls = [ 'https://chongqing.anjuke.com/sale/' ] def parse(self, response): for href in response.xpath('//div[@class="property-content-title"]/a/@href'): yield response.follow(href, self.parse_property) next_page = response.xpath('//a[@class="aNxt"]/@href') if next_page: yield response.follow(next_page[0], self.parse) def parse_property(self, response): yield { '楼盘': response.xpath('//h1/text()').get(), '地址': response.xpath('//address/text()').get(), '单价': response.xpath('//th[contains(text(), "单价")]/following-sibling::td/text()').get(), '总价': response.xpath('//th[contains(text(), "总价")]/following-sibling::td/text()').get(), '户型': response.xpath('//th[contains(text(), "户型")]/following-sibling::td/text()').get(), '面积': response.xpath('//th[contains(text(), "面积")]/following-sibling::td/text()').get(), '建造年代': response.xpath('//th[contains(text(), "建造年代")]/following-sibling::td/text()').get(), } ``` 代码中,我们定义了一个名为`AnjukeSpider`的Spider类,它会爬取`https://chongqing.anjuke.com/sale/`页面上的二手房信息,包括楼盘、地址、单价、总价、户型、面积、建造年代。 在`parse`方法中,我们使用XPath选择器找到所有房源链接,并使用`response.follow`方法进行跟进。同时,我们也找到下一页的链接并跟进。 在`parse_property`方法中,我们使用XPath选择器找到房源页面的各种信息,并使用`yield`关键字将这些信息返回。 最后,在命令行中进入项目根目录,运行以下命令启动爬虫: ``` scrapy crawl anjuke -o anjuke.csv ``` 这个命令会将爬取到的数据保存到`anjuke.csv`文件中。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rubyw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值