# -*- coding: utf-8 -*-
import requestsÂ
import re
from bs4 import BeautifulSoup #å¯¼å ¥bs4ä¸çBeautifulSoup
import pymysql
db = pymysql.connect(host='localhost',
               user='root',
               password='mysql123',
               db='58tc',
               charset='utf8mb4',
               cursorclass=pymysql.cursors.DictCursor)
# cursor.execute("DROP TABLE IF EXISTS employee") å建mysqlçtable,å 为ææ©å建好äºï¼è¿æ®µæ³¨éæäº
# sql1 = """CREATE TABLE employee(
# AREA VARCHAR(20) ,
# SPACE VARCHAR(20),
# TIME VARCHAR(20),
# PRINCE VARCHAR(20),
# HREF VARCHAR(300))"""
# cursor.execute(sql1)
# 使ç¨cursor()æ¹æ³è·åæä½æ¸¸æ
cursor = db.cursor()
sql = "INSERT INTO EX(`AREA`,`SPACE`,`TIME`,`PRINCE`,`HREF`) VALUES (%s,%s,%s,%s,%s)" Â Â Â Â
def urls(url):  #å®ä¹ä¸ä¸ªå ¥å£ï¼return解æè¿çç½åæºç
  res = requests.get(url)Â
  res.encoding='utf-8'
  soup=BeautifulSoup(res.text,'html.parser')
  return soup
url=['http://sz.58.com/nanshan/zufang/0/?minprice=0_1600&PGTID=0d300008-0071-3991-2740-1076d93269e7&ClickID=2']
for x in range(2,13):      #å 为58ååç页é¢ç½åæ¯ç±JS计ç®èå¾çï¼æ»ç»è§å¾åç°æ¯ä¸ä¸uä¸ç'pn?'ä¸âï¼â为页ç
  u='http://sz.58.com/nanshan/zufang/0/pn'+str(x)+'/?minprice=0_1600'
  url.append(u)
for y,m in zip(url,range(13)):  #yå°±æ¯ææurlï¼urls(url)å°±è½è§£æææçurl
  soup=urls(y)
  for info,n in zip(soup.select('li'),range(35)):
    space=info.select('.des .room')[0].text
    c=info.select('.listliright .sendTime')[0].text.replace("      ",'')
    a=info.select('.listliright .money')[0].text
    SPACE = re.findall('.室.å .å«',space)      #ç±äº58å¾å°çä¿¡æ¯ä¸åå¾å¤ç©ºæ ¼ï¼èä¸æ æ³ç¨strip(ï¼å»é¤ï¼è¿é使ç¨äºrepalaceï¼å ä¸re
    AREA = re.findall('..ã¡',space)         #两ç§æ¹æ³ç»å使ç¨ï¼å»é¤äºç©ºæ ¼ï¼å¾å°äºä¸ä¸ªList
    TIME = re.findall('\r\n(....)',c)
    PRINCE = re.findall('\n(.......)',a)
    HREF1 = info.select('.des a')[0]['href']
    HREF2 = HREF1+'?from='+str(m)+'-list-'+str(n)
    HREF = [HREF2]
    # print(AREA, SPACE, TIME, PRINCE, HREF)
    if(TIME == []):                  #ç¬åçTIMEåSPACEä¸æ空å¼ï¼æ¤å¤ç¨IFç®åå¤ç
      TIME = ['NULL']
    if (SPACE == []):
      SPACE = ['NULL']
    cursor.execute(sql, (AREA, SPACE, TIME, PRINCE, HREF))  #è¿ééå·åé¢è¦å ç©ºæ ¼ï¼ä¸ç¶æ æ³å¯¼å ¥MySQL
    db.commit()
db.close()