爬虫项目二十:用Python对58租房信息进行爬取


前言

用Python爬下58同城租房详情信息 (仅供学习使用,已发现弊端 封IP严重)


提示:以下是本篇文章正文内容,下面案例可供参考

一、分析url

第一页:https://bj.58.com/chuzu/?PGTID=0d000000-0000-0116-5fa7-7c361aef2ca6&ClickID=1
第二页:https://bj.58.com/chuzu/pn2/?PGTID=0d3090a7-0000-1606-2950-91e1fdc3a82a&ClickID=2

删除无用参数修改后:
https://城市首字母.58.com/chuzu/pn页数/

二、制造url

上面我们已经知道了url的组成规律,我们就可以批量生成url

实例代码如下:

def City_Urls(self):
    urls=[]
    keyword=input("请输入城市首字母:")
    start_page=input("请输入起始页数:")
    end_page=input("请输入结束页数:")
    for i in range(int(start_page),int(end_page)+1):
        url="https://%s.58.com/chuzu/pn%d/"%(keyword,i)
        urls.append(url)
    return urls

三、详情url

我们的目的是通过列表页面获取详情页url进入详情页面获取数据,所以在我们已经获取了列表页url后就该获取每个房源的详情页url,我们在浏览器上右键检查元素,定位每个房源标题可看到详情url

在这里插入图片描述
根据上面我们便可以写代码获取每个房源的详情页url

实例代码如下:

def Get_Detail_Link(self,url):
    text=requests.get(url=url).text
    html=etree.HTML(text)
    detail_urls=html.xpath('//ul[@class="house-list"]/li/div[@class="des"]/h2[1]/a[1]/@href')
    self.detail_list.extend(detail_urls)

四、解析页面

有了详情页的url我们便可以通过解析数据 保存数据,我们要获取的数据是下图中的一些数据

在这里插入图片描述
关于这些元素信息的获取,用re也好、XPath也可 不管用什么方法 获取到数据就行,我用的是XPath,步骤不详写,直接看代码

实例代码如下:

def Parser_Data(self,detail_url):
    dic={}
    text=requests.get(url=detail_url,headers=self.header).text
    html=etree.HTML(text)
    try:
        dic["house-title"]=html.xpath('//div[@class="house-title"]/h1[1]/text()')[0]
    except:
        dic["house-title"]=""
    try:
        dic["time"]="".join(html.xpath('//div[@class="house-title"]/p[@class="house-update-info c_888 f12"]//text()')).replace("\n","").replace("\xa0","")
    except:
        dic["time"] =""
    try:
        dic["price"]="".join(html.xpath('//div[@class="house-pay-way f16"]/span[1]//text()')).replace("\n","").replace("\xa0","")
    except:
        dic["price"] = ""
    try:
        dic["instructions1"]=html.xpath('//div[@class="house-pay-way f16"]/span[2]/text()')[0]
    except:
        dic["instructions1"] =""
    try:
        dic["instructions2"] = html.xpath('//div[@class="house-pay-way f16"]/span[last()]/text()')[0]
    except:
        dic["instructions2"] =""
    with open(".//house.csv", "a", encoding="utf-8") as f:
        writer = csv.DictWriter(f, dic.keys())
        writer.writerow(dic)

总结

这次爬虫,通过找到列表页的url规律批量生成列表页url,通过列表页url 获取详情页url,以此获取数据

如果你对爬虫感兴趣,欢迎到我主页浏览,现已经更新多个爬虫项目,所以源码均在公众号“阿虚学Python”中,本篇文章源码,回复“58租房”获取
在这里插入图片描述
谢谢大家的观看,如果觉得不错就点个赞吧,你的赞是对原创博主最大的支持

  • 2
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,我们可以使用 Python 中的 requests 库和 BeautifulSoup 库来实现爬取 58 同城租房信息的功能。具体步骤如下: 1. 导入所需库: ```python import requests from bs4 import BeautifulSoup ``` 2. 构造 URL 并发送请求: ```python url = 'https://hz.58.com/chuzu/pn1/' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299' } response = requests.get(url, headers=headers) ``` 3. 解析 HTML 并提取数据: ```python soup = BeautifulSoup(response.text, 'html.parser') house_list = soup.select('.list > li') for house in house_list: title = house.select('.des > h2 > a')[0].text.strip() price = house.select('.money > b')[0].text.strip() house_type = house.select('.room > p')[0].text.strip() location = house.select('.add > a')[0].text.strip() print(title, price, house_type, location) ``` 完整代码如下: ```python import requests from bs4 import BeautifulSoup url = 'https://hz.58.com/chuzu/pn1/' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299' } response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') house_list = soup.select('.list > li') for house in house_list: title = house.select('.des > h2 > a')[0].text.strip() price = house.select('.money > b')[0].text.strip() house_type = house.select('.room > p')[0].text.strip() location = house.select('.add > a')[0].text.strip() print(title, price, house_type, location) ``` 这样就完成了爬取 58 同城租房信息的功能。需要注意的是,爬虫涉及到的数据抓取和使用需要遵守相关法律法规,如有违反后果自负。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值