使用爬虫抓取浦城房产信息

一个朋友让我帮忙找老家的房子,可是链家,安居客这些地方都没有浦城的房产信息,后来在一个论坛里找到了还算比较活跃的房地产板块,于是以此为基础抓取信息。
遇到的坑:
1、论坛帖子式的帖子,格式不太规范
2、信息中包含出售,出租

import requests
from bs4 import BeautifulSoup



with open(r'c:\pc.csv','a',encoding='utf-8') as f:
    f.write('{},{},{},\n'.format('链接','更新时间','房源信息'))
    for i in range(1,50):
        url = 'https://bbs.pc186.com/forum-79-'+str(i)+'.html'
        print(url)
        headers = {
     
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.66'
        }

        html = requests.get(url,headers = headers).text
        soup = BeautifulSoup(html,'html.parser')
        # print(soup)
        infos = soup.find('div',{
     'class':'bm_c'}).find_all('tbody')
        # print(infos)
        # break
        data_list=[]
        for info in infos[1:]:
            # print(info)
            # break

            name = info.find('a',{
     'class':'s xst'}).text
            # print(name)
            date = info.find('td',{
     'class':'by'}).find('em').find('span').text
            print(date)

            pages = info.find('th').find_all('a')
            i=0
            for page in pages:
                data = page.get('href')
                i=i+1
                if i ==4:
                    link = data
                    # 接下来是存入csv
                    f.write('{},{},{},\n'.format(link,date,name))

你可能感兴趣的:(爬虫,Python,python,html,爬虫)