前面已经进行了爬虫基础部分的学习,于是自己也尝试爬了一些网站数据,用的策略都是比较简单,可能有些因素没有考虑到,但是也爬取到了一定的数据,下面介绍两个爬过的案例。
链家网站爬取
链家网站的爬取不难,我爬取的主要是租房数据,看一下页面:

我需要爬取的字段有房子的名称,小区,面积,朝向,户型,以及房租。
代码比较简单,主要使用了requests和xpath进行爬取,爬取了100页得数据。
import requests
import pandas as pd
import re
from lxml import etree
url = 'https://bj.lianjia.com/zufang/pg'
resp = requests.get(url)
time.sleep(0.5)
resp_text = resp.text
tree = etree.HTML(resp.text)
info_list = tree.xpath('//div[@class="content__list"]/div')
for info in info_list:
name = info.xpath('./a/@title')
#detail_1 = info.xpath('.//div[@class="content__list--item--main"]/p[2]//text()')
location = info.xpath('.//div[@class="content__list--item--main"]/p[2]/a/text()')
detail_list = info.xpath('.//div[@class="content__list--item--main"]/p[2]/text()')
detail_string = ''.join(detail_list)
detail_text = re.sub('[\r\n\t\s//\-]', '', detail_string)
price = tree.xpath('//*[@id="content"]/div[1]/div[1]/div[1]/div/span//text()')
price = ''.join(price)
#detail_1 = info.xpath('.//div[@class="content__list--item--main"]/p/a/text()')
#detail_2 = info.xpath('.//div[@class="content__list--item--main"]/p/i/text()')
print(name,location,detail_text,price)
f.write("{},{},{},{}\n".format(name,location,detail_text,price))
上面给的代码是爬取一个页面的,如果要爬取多个页面写个循环就好了。爬取保存后得数据如下图:

保存格式可以自行调整成自己想要的格式。
难点分析

本文介绍了作者使用Python爬虫分别爬取链家租房和实习僧网站数据的经验。在链家租房部分,通过requests和xpath获取了房源信息,但因访问限制仅获取了100页数据。实习僧网站则面临字体反爬问题,通过解析编码规则获取数据。目前,实习僧数据爬取已解决字体反爬,但链家数据获取存在未解决的访问限制问题。
最低0.47元/天 解锁文章
2416

被折叠的 条评论
为什么被折叠?



