1 from selenium import webdriver#导入库 2 from bs4 import BeautifulSoup 3 import urllib,pymysql 4 db = pymysql.connect(host='*****', user='*****', password='*****', port=*****, 5 db='*****') 6 cursor = db.cursor() 7 table = '福州链家' 8 cursor.execute('create table 福州链家(区域 varchar(255)' 9 ',单价 varchar(255)' 10 ',总价 varchar(255)' 11 ',房屋户型 varchar(255)' 12 ',所在楼层 varchar(255)' 13 ',建筑面积 varchar(255)' 14 ',户型结构 varchar(255)' 15 ',套内面积 varchar(255)' 16 ',建筑类型 varchar(255)' 17 ',房屋朝向 varchar(255)' 18 ',建成年代 varchar(255)' 19 ',装修情况 varchar(255)' 20 ',建筑结构 varchar(255)' 21 ',供暖方式 varchar(255)' 22 ',梯户比例 varchar(255)' 23 ',配备电梯 varchar(255)' 24 ',链家编号 varchar(255)' 25 ',交易权属 varchar(255)' 26 ',挂牌时间 varchar(255)' 27 ',房屋用途 varchar(255)' 28 ',房屋年限 varchar(255)' 29 ',房权所属 varchar(255))') 30 31 browser = webdriver.Chrome()#声明浏览器 32 url = 'https://fz.lianjia.com/chengjiao/' 33 browser.get(url)#打开浏览器预设网址 34 source = browser.page_source#打印网页源代码 35 soup = BeautifulSoup(source, 'lxml') 36 ul_list = soup.select('div.content')[0] 37 position = {} 38 for li in ul_list.select('li'): 39 if(li.select('a.img')): 40 websites =li.select('a.img')[0].get('href') 41 browser.get(websites) 42 soup = BeautifulSoup(browser.page_source, 'lxml') 43 44 outlist = list() 45 quyu = browser.find_element_by_xpath("/html/body/div[4]/div").text 46 outlist = quyu.split() 47 position['区域'] = outlist[0] 48 position['单价'] = browser.find_element_by_xpath("/html/body/section[1]/div[2]/div[2]/div[1]/b").text 49 position['总价'] = browser.find_element_by_xpath("/html/body/section[1]/div[2]/div[2]/div[1]/span/i").text 50 51 baseC = soup.select('div.introContent')[0].select('div.base')[0].select('div.content')[0] 52 for ba in baseC.select('li'): 53 keys = ba.text[:4] 54 position[keys] = ba.text[4:].strip() 55 #基本信息 56 other = soup.select('div.introContent')[0].select('div.transaction')[0].select('div.content')[0] 57 for ot in other.select('li'): 58 keys = ot.text[:4] 59 position[keys] = ot.text[4:].strip() 60 #其他信息 61 print(position) 62 63 64 keys = ', '.join(position.keys()) 65 values = ', '.join(['%s'] * len(position)) 66 sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, 67 keys=keys, values=values) 68 print(sql) 69 try: 70 cursor.execute(sql, tuple(position.values())) 71 db.commit() 72 except Exception as e: 73 print('错误信息为', e) 74 db.rollback() 75 db.close()