批处理之家's Archiver

ivor 发表于 2016-2-23 15:23

python 爬虫之获取bathome论坛的最新标题,最新回复,热门主题

拿本论坛作为演示目标网站,实属演示,如有问题,告知删除

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

中文文档:[url]http://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/[/url]     
[quote]Beautiful Soup会帮你节省数小时甚至数天的工作时间.[/quote]
截止我发表Beautiful Soup 4.2.0已经更新了,而且支持python 3.5[code]#!/usr/bin/env python
# python 3.5.1
import bs4, urllib.request, os

def bathome(soup,idstring):
    homegrids = soup.find(id = idstring)
    a = homegrids.find_all('a')
    #print(homegrids.find_all('a'))
    count = 0
    for i in a:
        count += 1
        if count % 2 == 0:
            print('%-15s文章:%3s' % (str, i.string))
        else:
            str = '用户:%s' % i.string

url = 'http://www.bathome.net/'
web = urllib.request.urlopen(url)
soup = bs4.BeautifulSoup(web,'html.parser')
print("最新主题:")
bathome(soup, 'homegrids_c_1')
print("最新回复:")
bathome(soup, 'homegrids_c_2')
print("热门主题:")
bathome(soup, 'homegrids_c_3')

[/code]

bailong360 发表于 2016-2-23 22:31

更小更清晰~

codegay 发表于 2016-2-24 16:47

:lol 白龙好像就是站长。。你放心好了。

bailong360 发表于 2016-2-28 16:11

[b]回复 [url=http://www.bathome.net/redirect.php?goto=findpost&pid=182536&ptid=39463]3#[/url] [i]codegay[/i] [/b]
我一个小中尉啥时候成站长了
站长是Batcher

codegay 发表于 2016-2-28 16:25

[b]回复 [url=http://bbs.bathome.net/redirect.php?goto=findpost&pid=182621&ptid=39463]4#[/url] [i]bailong360[/i] [/b]


    :lol 哦,那就是我弄错了。

CrLf 发表于 2016-2-28 21:47

[b]回复 [url=http://www.bathome.net/redirect.php?goto=findpost&pid=182624&ptid=39463]5#[/url] [i]codegay[/i] [/b]


    啥?这么说你也不是站长?

codegay 发表于 2016-2-28 21:51

[b]回复 [url=http://bbs.bathome.net/redirect.php?goto=findpost&pid=182632&ptid=39463]6#[/url] [i]CrLf[/i] [/b]


    哈哈。好我要当站长。

页: [1]

Powered by Discuz! Archiver 7.2  © 2001-2009 Comsenz Inc.