#pip install lxml
#pip install requests
#发送请求
import requests
from lxml import etree
for i in range(1,4):
resp = requests.get(f'https://newhouse.fang.com/house/s/b9{i}/') #爬取信息的网站,有分页,i是第几页
#解析数据
resp.encoding = 'utf-8' #注意一定要先去检查控制台的中文编码信息 输入:document.charset回车
e = etree.HTML(resp.text)
#xpath获取想要的数据
names = [n.strip() for n in e.xpath('//div[@class="nlcd_name"]/a/text()')] #把每个数据返回到n 楼盘名称
addresses = e.xpath('//div[@class="address"]/a/@title') #楼盘位置
prices = [d.xpath('string(.)').strip() for d in e.xpath('//div[@class="nhouse_price"]')] #获取房价,此时有单位有数字,则需要遍历
#处理数据
data = []
for n,a,p in zip(names,addresses,prices):
data.append( [n,a,p])
'''
https://newhouse.fang.com/house/s/b91/
https://newhouse.fang.com/house/s/b92/
'''
#数据分析
import pandas
df = pandas.DataFrame(data,columns = ['小区名称','地址','价格'])
print(df)
爬取房天下
于 2024-02-18 14:43:28 首次发布