今天呢,我来爬取一下链家,拿到一些数据,方便后面进行数据分析。
首先,打开主页:
观察网页信息,发现不是Ajax请求,就是一个简单的获取就行了。
我们开始办事情:
可以看到,这段信息在源码中是这样的。
请求状态码是200,证明请求成功了。
我们现在来获取数据
已经把数据爬取下来了。
我们要把图上的数据都爬取下来,保存到本地
代码走:
import requests
from lxml import etree
url = "https://bj.lianjia.com/ershoufang/pg{}rs北京/"
for i in range(1,2):
print(i)
url_str=url.format(i)
print(url_str)
headers={
"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36"}
res=requests.get(url_str,headers=headers)
# print(res.content.decode())
html=res.content.decode()
html_1=etree.HTML(html)
houseInfo=html_1.xpath('//div[@class="houseInfo"]/text()')
title=html_1.xpath('//div[@class="title"]/a/text()')
positionInfo=html_1.xpath('//div[@class="positionInfo"]/a/text()')
totalPrice=html_1.xpath('//div[@class="totalPrice"]/span/text()')
unitPrice=html_1.xpath('//div[@class="unitPrice"]/span/text()')
followInfo=html_1.xpath('//div[@class="followInfo"]/text()')
tag=html_1.xpath('//div[@class="tag"]/span/text()')
print("****************")
print(title)
print("****************")
print(positionInfo)
print("****************")
print(houseInfo)
print("****************"