爬取房天下(http://newhouse.cd.fang.com/house/s/)成都地区的新房信息。
打开http://newhouse.cd.fang.com/house/s/,F12进入控制台
点击控制台的左上角的按钮,这是你可以将鼠标移至房天下页面的任何一个地方然后单击,你就可以看到该地方在html代码中的位置,比如:我点击红色区域的文本,那么在控制台中就会出现该文本在html代码中的位置。分析html代码,了解页面结构,然后获取你需要爬取内容在html代码中的路径,再稍微做些整理,就可以得到你想要爬取的内容。我主要用的是beautifulsoup。
代码讲解:
1.此段代码主要是获取成都地区新房信息在此网站上分成了多少页,之后通过循环的方式将每一页的信息都爬取出来。
URL = 'http://newhouse.cd.fang.com/house/s/b91/' HTML = requests.get(URL) SOUP = BeautifulSoup(HTML.content, 'html.parser', from_encoding='gb18030') last_page = SOUP.select('.last') page_number = int(last_page[0]['href'].split('/')[3].split('9')[1]) print(page_number)
2.此段代码是解析了我要获取的四项信息,包括:小区名字,所在详细地址,当前所处状态,价格。将四项信息分别存入四个数组。
names_list = [] adresses_list = [] all_type_list = [] all_money_list = [] url_demo = 'http://newhouse.cd.fang.com/house/s/b9{}/' for i in range(1,(page_number+1)): url = url_demo.format(i) html = requests.get(url) soup = BeautifulSoup(html.content,'html.parser',from_encoding='gb18030') names = soup.select('.nlcd_name a') adresses = soup.select('.address a') for name in names: names_list.append(name.text.strip()) for adress in adresses: adress_detail = re.findall(r'".+"',str(re.findall(r'title=".+"',str(adress))))[0] adresses_list.append(adress_detail.split('"')[1]) all_type = soup.findAll(name="span", attrs={"class":re.compile(r"forSale|inSale|outSale|zusale|zushou")}) for type in all_type: all_type_list.append(type.text) if soup.select('.kanzx'): all_money_list.append('无') all_money = soup.findAll(name="div", attrs={"class":re.compile(r"nhouse_price|kanesf")}) for money in all_money: all_money_list.append(money.text.strip()) else: all_money = soup.findAll(name="div", attrs={"class":re.compile(r"nhouse_price|kanesf")}) for money in all_money: all_money_list.append(money.text.strip())3.遍历四个数组,见信息输出,最后保存在一个excel中。
all_message = [] for m in range(0,len(names_list)): message = [names_list[m],adresses_list[m],all_type_list[m],all_money_list[m]] print(message) all_message.append(message) df = pandas.DataFrame(all_message) df.to_excel('house_price.xlsx') print(df)
一共有726条信息。