博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用python爬取安居客苏州的房价数据
阅读量:7054 次
发布时间:2019-06-28

本文共 2026 字,大约阅读时间需要 6 分钟。

下面是我用python爬取的房价数据,程序可以跑完,但是不知何故。数据库中并没有收到数据?请大家帮忙看看

 

#这里导入我们需要用的模块,并连接SQLyog,并创建游标 import requestsimport refrom lxml import etreeimport pymysqlimport timeconn=pymysql.connect(host='localhost',user='root',passwd='1234',db='mydatabase1',port=3306,charset='utf8')cursor=conn.cursor()#获取头命令,进行伪装访问浏览器,避免爬取失败被封IP:headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}#创建一个获取网址的函数:def get_house_url(url): html=requests.get(url,headers=headers)#利用头命令进行伪装访问网址 selector=etree.HTML(html.text) #解析源代码,使之成为我们需要的文本文档 house_hrefs=selector.xpath('//div[@class="house-title"]/a/@href')#获取连接 for house_href in house_hrefs: get_house_info(house_href) def get_house_info(url): #获取连接里面的具体信息 html=requests.get(url,headers=headers) selector=etree.HTML(html.text) #利用头命令进行访问浏览器并把源代码解析成文本文档 try: name=selector.xpath('//*[@id="content"]/div[2]/h3/text()')[0] #以下依次都是进行抓取有效的数据, village=selector.xpath('//*[@id="content"]/div[3]/div[1]/div[3]/div/div[1]/div/div[1]/dl[1]/dd/a/text()')[0] price=selector.xpath('//*[@id="content"]/div[3]/div[1]/div[1]/span[1]/em/text()')[0] style=selector.xpath('//*[@id="content"]/div[3]/div[1]/div[3]/div/div[1]/div/div[2]/dl[1]/dd/text()')[0] area=selector.xpath('//*[@id="content"]/div[3]/div[1]/div[1]/span[3]/em/text()')[0] unit_price=selector.xpath('//*[@id="content"]/div[3]/div[1]/div[3]/div/div[1]/div/div[3]/dl[2]/dd/text()')[0] cursor.execute("insert into suzhou_house(name,village,price,style,area,unit_price) values(%s,%s,%s,%s,%s,%s)",(str(name),str(village),str(price),str(style),str(area),str(unit_price))) except IndexError: pass

  if __name__=='__main__':

      urls=['https://suzhou.anjuke.com/sale/p{}-rd1/?kw=%E8%8B%8F%E5%B7%9E'.format(str(i)) for i in range(1,6)]
      for url in urls:
          get_house_url(url)
          time.sleep(2)
          conn.commit()

以上是我写的爬虫程序。但是不知何故。数据库SQLyog中并没有收到数据,请读者帮忙看看。

转载于:https://www.cnblogs.com/A1006438/p/8747371.html

你可能感兴趣的文章
敏捷宣言和企业Scrum作者Mike Beedle去世
查看>>
5G一周热闻:华为夺联通5G大单,首张5G电话卡发放
查看>>
调研对敏捷宣言2.0的需求
查看>>
微软在C# 8中引入预览版可空引用类型
查看>>
深究JavaScript——函数调用与this详解
查看>>
书评与访谈:Software Development Metrics
查看>>
re:Invent第二天:互联网客户在右传统客户在左,AWS向哪儿?
查看>>
云端能力知几许?12人众测华为云企业级Kubernetes集群实力
查看>>
《Elixir in Action》书评及作者问答录
查看>>
Apache HBase的现状和发展
查看>>
AlphaZero进化论:从零开始,制霸所有棋类游戏
查看>>
IBM中国开发中心吉燕勇: 通过Cloud Data Services打造新型认知计算数据分析云平台...
查看>>
作者问答:解密硅谷
查看>>
linux系统高并发socket最大连接数优化
查看>>
Netflix发布Polly.JS,一个用于HTTP交互的开源库
查看>>
敏捷团队中测试人员的角色
查看>>
GitHub推出Scientist,帮助开发者重构关键路径代码
查看>>
40%创业公司用伪AI忽悠钱,欧洲被AI时代抛弃了吗?
查看>>
AT&T签署8位数合同,设备商恐无法从5G获利
查看>>
Netflix Play API:我们为什么构建了一个演进式架构?
查看>>