鱼C论坛

 找回密码
 立即注册
查看: 1495|回复: 14

[已解决]爬虫大神快来围观,菜鸟又遇到进阶问题了

[复制链接]
发表于 2020-8-4 10:34:57 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 L嘉 于 2020-8-4 11:20 编辑

现在我只能爬到标题这些,但是我要爬取子页面的内容应该怎么写了呢?如下图,我要爬取子页面的栋数和户数,但是我这个写好的代码爬取没有反应怎么一回事啊


代码在最后

1415444.png 2424234.jpg 1212121212.jpg


  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Aug  4 09:24:02 2020

  4. @author: Administrator
  5. """

  6. from lxml import etree
  7. import requests
  8. import csv
  9. from multiprocessing.dummy import Pool as pl    #导入线程池

  10. def towrite(item):
  11.     with open('balk.csv','a',encoding='utf-8') as csvfile:
  12.         writer = csv.writer(csvfile)
  13.         try:
  14.             writer.writerow(item)
  15.         except:
  16.             print('write error!')
  17.             
  18.             
  19. def spider(url):
  20.     htm = requests.get(url, headers = headers)
  21.     response=etree.HTML(htm.text)
  22.    
  23.     mingcheng = response.xpath('div[1]/div[1]/a/text()')[0]
  24.    
  25.     zaishou = response.xpath('div[2]/div[2]/a/span/text()')[0]
  26.    
  27.     junjia = response.xpath('div[2]/div[1]/div[1]/span/text()')[0]
  28.    
  29.     dongshu = response.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[3]/div[5]/span[2]/text()')[0]
  30.    
  31.     hushu = response.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[3]/div[6]/span[2]/text()')[0]
  32.    
  33.     xiaoqu_item = [mingcheng,zaishou,junjia,dongshu,hushu]
  34.     towrite(xiaoqu_item)
  35.     print('正在爬取小区:',mingcheng)
  36.    
  37.    
  38.     if __name__ == '__main__':
  39.        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.3'}
  40.    
  41.     start_url = 'https://cd.ke.com/xiaoqu/damian/pg'
  42.     pool=pl(4)
  43.     all_url = []
  44.     for x in range(1,4):
  45.         html = requests.get(start_url +str(x), headers=headers)
  46.         slector = etree.HTML(html.text)
  47.         xiaoqulist = slector.xpath('//*[@id="beike"]/div[1]/div[4]/div[1]/div[3]/ul/li')
  48.         for xiaoqu in xiaoqulist:
  49.             xiaoqu_url_houduan = xiaoqu.xpath('//*[@id="beike"]/div[1]/div[4]/div[1]/div[3]/ul/li[1]/div[1]/div[1]/a')[0]
  50.             all_url.append(xiaoqu_url_houduan)
  51.     pool.map(spider,all_url)
  52.     pool.close()
  53.     pool.join()
复制代码
最佳答案
2020-8-4 20:58:18


帮你改完了,应该能达到你的目的了:

6.png

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Aug  4 09:24:02 2020

  4. @author: Administrator
  5. """

  6. from lxml import etree
  7. import requests
  8. import csv
  9. from multiprocessing.dummy import Pool as pl  # 导入线程池


  10. def towrite(item):
  11.     with open('balk.csv', 'a', encoding='utf-8') as csvfile:
  12.         writer = csv.writer(csvfile)
  13.         try:
  14.             writer.writerow(item)
  15.         except:
  16.             print('write error!')


  17. def spider(url):
  18.     htm = requests.get(url, headers=headers)
  19.     response = etree.HTML(htm.text)

  20.     mingcheng = response.xpath('//div[@class="title"]/h1/text()')[0].strip()

  21.     dongshu = response.xpath('//span[@class="xiaoquInfoContent"]/text()')[4]

  22.     hushu = response.xpath('//span[@class="xiaoquInfoContent"]/text()')[5]

  23.     for i in xiaoquname:
  24.         if mingcheng in i[0]:
  25.             idx = i[0].index(mingcheng)
  26.             zaishou = i[1][idx][0]
  27.             junjia = i[1][idx][1]
  28.             break

  29.     xiaoqu_item = [mingcheng, zaishou,junjia,dongshu, hushu]
  30.     towrite(xiaoqu_item)
  31.     print('正在爬取小区:', mingcheng)


  32. if __name__ == '__main__':
  33.     headers = {
  34.         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.3'}

  35.     start_url = 'https://cd.ke.com/xiaoqu/damian/pg'
  36.     pool = pl(4)
  37.     all_url = []
  38.     xiaoquname = []
  39.     for x in range(1, 4):
  40.         html = requests.get(start_url + str(x), headers=headers)
  41.         slector = etree.HTML(html.text)
  42.         xiaoqulist = slector.xpath('//div[@class="info"]/div[@class="title"]/a/@href')
  43.         name = slector.xpath("//a[@class='maidian-detail']/text()")
  44.         jiage = slector.xpath("//div[@class='totalPrice']/span/text()")
  45.         zaishous = slector.xpath("//a[@class='totalSellCount']/span/text()")
  46.         xiaoquname.append([name, list(zip(zaishous,jiage))])
  47.         for xiaoqu in xiaoqulist:
  48.             all_url.append(xiaoqu)
  49.     pool.map(spider, all_url)
  50.     pool.close()
  51.     pool.join()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-8-4 10:53:12 | 显示全部楼层
用代码编辑器传上来,复制的可能格式不对
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-4 11:05:11 | 显示全部楼层
在 spider 函数里

  1. global headers
复制代码
要把 headers 变成全局变量
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-4 11:20:33 | 显示全部楼层
1q23w31 发表于 2020-8-4 10:53
用代码编辑器传上来,复制的可能格式不对

好的,你在帮忙看看
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-4 11:22:32 | 显示全部楼层
liuzhengyuan 发表于 2020-8-4 11:05
在 spider 函数里

要把 headers 变成全局变量

还是没反应,空的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-4 12:20:37 | 显示全部楼层
L嘉 发表于 2020-8-4 11:22
还是没反应,空的

你的 xpath 全部都是错误的呀,你要爬取哪些内容

zaishou 是什么

junjia 是什么

dongshu

hushu
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-4 13:03:05 | 显示全部楼层
Twilight6 发表于 2020-8-4 12:20
你的 xpath 全部都是错误的呀,你要爬取哪些内容

zaishou 是什么

主要是子页面的爬取不会
1112.png 123131.png
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-4 14:10:38 | 显示全部楼层
L嘉 发表于 2020-8-4 13:03
主要是子页面的爬取不会

晚点帮你写吧,现在有点事哈~
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-4 14:32:29 | 显示全部楼层
Twilight6 发表于 2020-8-4 14:10
晚点帮你写吧,现在有点事哈~

谢谢
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-4 15:01:41 | 显示全部楼层
本帖最后由 johnnyb 于 2020-8-4 15:17 编辑

用我写的规则.. 亲测 没有任何问题.

  1. import requests
  2. from lxml import etree

  3. headers = {
  4.     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'
  5. }
  6. url = 'https://cd.ke.com/xiaoqu/1611057941003/?fb_expo_id=343036232051900416'
  7. r = requests.get(url=url, headers=headers, timeout=3)

  8. tree = etree.HTML(r.text)
  9. money = tree.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[2]/div/span[1]/text()')[0]
  10. WY = tree.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[3]/div[2]/span[2]/text()')[0].lstrip().rstrip()
  11. WYGS = tree.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[3]/div[3]/span[2]/text()')[0]
  12. KFS = tree.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[3]/div[4]/span[2]/text()')[0]
  13. tag = tree.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[3]/div[5]/span[2]/text()')[0]
  14. tag2 = tree.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[3]/div[6]/span[2]/text()')[0]
  15. print('参考价格:{0}元/平'.format(money))
  16. print('物业费:{0}'.format(WY))
  17. print('物业公司:{0}'.format(WYGS))
  18. print('开发商:{0}'.format(KFS))
  19. print('楼栋总数:{0}'.format(tag))
  20. print('房屋总数:{0}'.format(tag2))
复制代码


  1. 参考价格:17235元/平
  2. 物业费:1.29至5.2元/平米/月
  3. 物业公司:成都安达祥和置业有限公司
  4. 开发商:成都志达房地产开发有限公司
  5. 楼栋总数:69栋
  6. 房屋总数:5067户
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-8-4 17:16:36 | 显示全部楼层
johnnyb 发表于 2020-8-4 15:01
用我写的规则.. 亲测 没有任何问题.

那我要爬取每个小区的呢怎么写呢
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-4 17:26:19 | 显示全部楼层
本帖最后由 1q23w31 于 2020-8-4 17:37 编辑
L嘉 发表于 2020-8-4 17:16
那我要爬取每个小区的呢怎么写呢

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Aug  4 09:24:02 2020

  4. @author: Administrator
  5. """

  6. from lxml import etree
  7. import requests
  8. import csv
  9. from multiprocessing.dummy import Pool as pl    #导入线程池

  10. def towrite(item):
  11.     with open('balk.csv','a') as csvfile:
  12.         writer = csv.writer(csvfile)
  13.         try:
  14.             writer.writerow(item)
  15.         except:
  16.             print('write error!')
  17.             
  18.             
  19. def spider(url):
  20.     htm = requests.get(url, headers = headers)
  21.     response=etree.HTML(htm.text)
  22.    
  23.     mingcheng = response.xpath('//*[@id="beike"]/div[1]/div[2]/div[2]/div/div/div[1]/h1/@title')
  24.    
  25.    
  26.     junjia = response.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[2]/div/span[1]/text()')

  27.     dongshu = response.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[3]/div[5]/span[2]/text()')
  28.    
  29.     hushu = response.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[3]/div[6]/span[2]/text()')
  30.    
  31.     xiaoqu_item = [mingcheng,junjia,dongshu,hushu]
  32.     towrite(xiaoqu_item)
  33.     print('正在爬取小区:',mingcheng)
  34.    
  35.    
  36. if __name__ == '__main__':
  37.    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.3'}

  38. start_url = 'https://cd.ke.com/xiaoqu/damian/pg'
  39. pool=pl(4)
  40. all_url = []
  41. zaishou = []
  42. for x in range(1,4):
  43.     html = requests.get(start_url +str(x), headers=headers)
  44.     slector = etree.HTML(html.text)
  45.     xiaoqulist = slector.xpath('//*[@id="beike"]/div[1]/div[4]/div[1]/div[3]/ul')


  46.     for xiaoqu in xiaoqulist:
  47.         xiaoqu_url_houduan = xiaoqu.xpath('//*[@id="beike"]/div[1]/div[4]/div[1]/div[3]/ul/li/a/@href')
  48.         price = xiaoqu.xpath('//*[@id="beike"]/div[1]/div[4]/div[1]/div[3]/ul/li/div[2]/div[2]/a/span/text()')
  49.         all_url.extend(xiaoqu_url_houduan)
  50.         zaishou.extend(price)

  51. pool.map(spider,all_url)
  52. pool.close()
  53. pool.join()
复制代码

不是很完美,除了在售,其他的都能写出
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-4 18:17:42 | 显示全部楼层
本帖最后由 1q23w31 于 2020-8-4 18:20 编辑
L嘉 发表于 2020-8-4 17:16
那我要爬取每个小区的呢怎么写呢

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Aug  4 09:24:02 2020

  4. @author: Administrator
  5. """

  6. from lxml import etree
  7. import requests
  8. import csv
  9. from multiprocessing.dummy import Pool as pl #导入线程池
  10. import re

  11. def towrite(item):
  12.     with open('balk.csv','a') as csvfile:
  13.         writer = csv.writer(csvfile)
  14.         try:
  15.             writer.writerow(item)
  16.         except:
  17.             print('write error!')
  18.             
  19.             
  20. def spider(url):
  21.     htm = requests.get(url, headers = headers)
  22.     response=etree.HTML(htm.text)
  23.    
  24.     mingcheng = response.xpath('//*[@id="beike"]/div[1]/div[2]/div[2]/div/div/div[1]/h1/@title')
  25.    
  26.     zaishou = response.xpath('/html/head/meta[9]/@content')
  27.     zaishou = re.findall('在售二手房源.*?套',zaishou[0])

  28.     junjia = response.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[2]/div/span[1]/text()')

  29.     dongshu = response.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[3]/div[5]/span[2]/text()')
  30.    
  31.     hushu = response.xpath('//*[@id="beike"]/div[1]/div[3]/div[1]/div[2]/div[3]/div[6]/span[2]/text()')
  32.    
  33.     xiaoqu_item = [mingcheng,zaishou,junjia,dongshu,hushu]
  34.     towrite(xiaoqu_item)
  35.     print('正在爬取小区:',mingcheng)
  36.    
  37.    
  38. if __name__ == '__main__':
  39.    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.3'}

  40. start_url = 'https://cd.ke.com/xiaoqu/damian/pg'
  41. pool=pl(4)
  42. all_url = []

  43. for x in range(1,4):
  44.     html = requests.get(start_url +str(x), headers=headers)
  45.     slector = etree.HTML(html.text)
  46.     xiaoqulist = slector.xpath('//*[@id="beike"]/div[1]/div[4]/div[1]/div[3]/ul')


  47.     for xiaoqu in xiaoqulist:
  48.         xiaoqu_url_houduan = xiaoqu.xpath('//*[@id="beike"]/div[1]/div[4]/div[1]/div[3]/ul/li/a/@href')
  49.         price = xiaoqu.xpath('//*[@id="beike"]/div[1]/div[4]/div[1]/div[3]/ul/li/div[2]/div[2]/a/span/text()')
  50.         all_url.extend(xiaoqu_url_houduan)


  51. pool.map(spider,all_url)
  52. pool.close()
  53. pool.join()
复制代码



                               
登录/注册后可看大图


完美解决
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-8-4 19:45:21 | 显示全部楼层
L嘉 发表于 2020-8-4 17:16
那我要爬取每个小区的呢怎么写呢

哥们你不是来做伸手党的. 要举一反三.  都给你写完了 你还能学到啥?   再说你都会用Pool了 xpath规则还不明白呢?  不会吧.
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 1

使用道具 举报

发表于 2020-8-4 20:58:18 | 显示全部楼层    本楼为最佳答案   


帮你改完了,应该能达到你的目的了:

6.png

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Aug  4 09:24:02 2020

  4. @author: Administrator
  5. """

  6. from lxml import etree
  7. import requests
  8. import csv
  9. from multiprocessing.dummy import Pool as pl  # 导入线程池


  10. def towrite(item):
  11.     with open('balk.csv', 'a', encoding='utf-8') as csvfile:
  12.         writer = csv.writer(csvfile)
  13.         try:
  14.             writer.writerow(item)
  15.         except:
  16.             print('write error!')


  17. def spider(url):
  18.     htm = requests.get(url, headers=headers)
  19.     response = etree.HTML(htm.text)

  20.     mingcheng = response.xpath('//div[@class="title"]/h1/text()')[0].strip()

  21.     dongshu = response.xpath('//span[@class="xiaoquInfoContent"]/text()')[4]

  22.     hushu = response.xpath('//span[@class="xiaoquInfoContent"]/text()')[5]

  23.     for i in xiaoquname:
  24.         if mingcheng in i[0]:
  25.             idx = i[0].index(mingcheng)
  26.             zaishou = i[1][idx][0]
  27.             junjia = i[1][idx][1]
  28.             break

  29.     xiaoqu_item = [mingcheng, zaishou,junjia,dongshu, hushu]
  30.     towrite(xiaoqu_item)
  31.     print('正在爬取小区:', mingcheng)


  32. if __name__ == '__main__':
  33.     headers = {
  34.         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.3'}

  35.     start_url = 'https://cd.ke.com/xiaoqu/damian/pg'
  36.     pool = pl(4)
  37.     all_url = []
  38.     xiaoquname = []
  39.     for x in range(1, 4):
  40.         html = requests.get(start_url + str(x), headers=headers)
  41.         slector = etree.HTML(html.text)
  42.         xiaoqulist = slector.xpath('//div[@class="info"]/div[@class="title"]/a/@href')
  43.         name = slector.xpath("//a[@class='maidian-detail']/text()")
  44.         jiage = slector.xpath("//div[@class='totalPrice']/span/text()")
  45.         zaishous = slector.xpath("//a[@class='totalSellCount']/span/text()")
  46.         xiaoquname.append([name, list(zip(zaishous,jiage))])
  47.         for xiaoqu in xiaoqulist:
  48.             all_url.append(xiaoqu)
  49.     pool.map(spider, all_url)
  50.     pool.close()
  51.     pool.join()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-24 20:29

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表