主要是想爬取湖北省武汉市江汉区的二手房数据:“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")