美文网首页web服务器
Spider_anjukeNewHouse

Spider_anjukeNewHouse

作者: GHope | 来源:发表于2018-10-31 12:46 被阅读10次

获取页面后使用bs4进行解析,熟悉除lxml解析的另一种页面解析方式。
本次爬取内容为安客居上新房的信息,主要包括新房区名称、新房所处具体位置。

爬取过程

因为安居客新房的信息只有两页,所以构建新房地址容器,用for遍历容器list中的元素依次作为访问的地址。获取页面 -- 解析页面 -- 保存本地json。

import json
import requests
from bs4 import BeautifulSoup


# 获取页面
def get_page(url):
    headers = {
        "User-Agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)"
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        text = response.content.decode('utf-8')
        return text
    return None


# 解析页面
def parse_soup(html):
    # 创建soup对象
    soup = BeautifulSoup(html,'lxml')
    # 解析小区名称
    result = soup.select('.items-name')
    house_name = result
    # 解析具体位置
    result = soup.select('.list-map')
    house_local = result
    # 解析出售价格
    # 因为网页上有很多暂未开盘的房市及未定价的房屋,所以暂且搁置
    # result = soup.select('.price' or '.around-price')
    # house_price = result
    # print(result)

    house = []
    for i in range(len(house_name)):
        item = {}
        item['name'] = house_name[i].text
        item['local'] = house_local[i].text.replace('\xa0','')
        # item['price'] = house_price[i].text
        house.append(item)
    return house


# 保存本地json数据
def write_json(items):
    house_json = json.dumps(items, ensure_ascii=False, check_circular=True)
    filename = './安居客攀枝花新楼'
    with open(filename, "a", encoding='utf-8') as f:
        f.write(house_json)



# 主程序
def main():
    urls = ['https://pzh.fang.anjuke.com/?from=navigation', 'https://pzh.fang.anjuke.com/loupan/all/p2/']
    for url in urls:
        html = get_page(url)
        items = parse_soup(html)
        write_json(items)


if __name__ == '__main__':
    main()

总结:

感觉两种解析方式都不是很顺手,也许是先入为主的思想作祟吧!相对来说比较倾向与lxml的xpath解析方式,也许本身对于页面元素更敏感一些。

GitHub地址

相关文章

  • Spider_anjukeNewHouse

    获取页面后使用bs4进行解析,熟悉除lxml解析的另一种页面解析方式。本次爬取内容为安客居上新房的信息,主要包括新...

网友评论

    本文标题:Spider_anjukeNewHouse

    本文链接:https://www.haomeiwen.com/subject/goxazftx.html