找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 25888|回复: 6

[原创教程] python 爬虫之获取bathome论坛的最新标题,最新回复,热门主题

[复制链接]
发表于 2016-2-23 15:23:15 | 显示全部楼层 |阅读模式
拿本论坛作为演示目标网站,实属演示,如有问题,告知删除

本文章旨在交流python下BS4的强大,对于整个网页页面的理解,就是作为一个对象,比如<a href='...' /a>,<div.../div>.每个元素都可以精确定位。包括注释部分
代码少,且能精确获取网页内容,如果你还在用正则截取内容,你就OUT了


中文文档:http://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/     
Beautiful Soup会帮你节省数小时甚至数天的工作时间.

截止我发表Beautiful Soup 4.2.0已经更新了,而且支持python 3.5
  1. #!/usr/bin/env python
  2. # python 3.5.1
  3. import bs4, urllib.request, os

  4. def bathome(soup,idstring):
  5.     homegrids = soup.find(id = idstring)
  6.     a = homegrids.find_all('a')
  7.     #print(homegrids.find_all('a'))
  8.     count = 0
  9.     for i in a:
  10.         count += 1
  11.         if count % 2 == 0:
  12.             print('%-15s文章:%3s' % (str, i.string))
  13.         else:
  14.             str = '用户:%s' % i.string

  15. url = 'http://www.bathome.net/'
  16. web = urllib.request.urlopen(url)
  17. soup = bs4.BeautifulSoup(web,'html.parser')
  18. print("最新主题:")
  19. bathome(soup, 'homegrids_c_1')
  20. print("最新回复:")
  21. bathome(soup, 'homegrids_c_2')
  22. print("热门主题:")
  23. bathome(soup, 'homegrids_c_3')

复制代码

评分

参与人数 2技术 +2 收起 理由
bailong360 + 1 好东西收藏
codegay + 1 1

查看全部评分

发表于 2016-2-23 22:31:46 | 显示全部楼层
更小更清晰~
发表于 2016-2-24 16:47:26 | 显示全部楼层
白龙好像就是站长。。你放心好了。
发表于 2016-2-28 16:11:31 | 显示全部楼层
回复 3# codegay
我一个小中尉啥时候成站长了
站长是Batcher
发表于 2016-2-28 16:25:31 | 显示全部楼层
回复 4# bailong360


    哦,那就是我弄错了。
发表于 2016-2-28 21:47:20 | 显示全部楼层
回复 5# codegay


    啥?这么说你也不是站长?
发表于 2016-2-28 21:51:52 | 显示全部楼层
回复 6# CrLf


    哈哈。好我要当站长。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-16 22:21 , Processed in 0.021038 second(s), 9 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

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