BeautifulSoup的简单使用

2017-09-02  本文已影响0人  Brave1991

最简单的爬虫程序,可以让初学者快速了解爬虫的过程。本文主要使用python3.0+配合BeautifulSoup完成豆瓣读书top250信息的抓取和整合。

豆瓣读书.png

首先下载并安装BeautifulSoup4,大致阅读下使用文档然后创建python文件,引用库文件信息如下:

import urllib.request
from bs4 import BeautifulSoup

主程序结构:

file = open("/Users/brave/Documents/python/top250.txt","w",encoding = "utf-8")
for i in range(0,250,25):
    URL = "https://book.douban.com/top250?start=" + str(i)
    print(URL)
    getAndSaveInfo(file,URL)
file.close()

说明:爬虫的书写没有绝对最佳的方式,规律的寻找有时候比技术更重要。通过点击不同页码,发现top250信息总是在同一个网址的基础上进行递增,故使用for循环,定位不同页面的网址,进而完成所有的解析。
由于需求简单,此程序仅需定义一个子函数getAndSaveInfo即可完成任务:

def getAndSaveInfo(file,URL):
    resp = urllib.request.urlopen(URL)
    html = resp.read()
    # print(html
    bssoup = BeautifulSoup(html,"html.parser")
    tables = bssoup.find_all("table")
    for table in tables:
        item = table.find("tr",class_="item")
        if(item):
            # print(item)
            content = item.find_all("td")[1]
            # print(content)
            title = content.find("div",class_="pl2").a["title"]
            # print(title)
            writerAndPrice = content.find("p",class_="pl").string.split("/")
            writerTemp = writerAndPrice[0]
            writer = writerTemp.split("]")[1] if(writerTemp[0] == "[") else writerTemp
            price =  writerAndPrice[len(writerAndPrice)-1]
            # print(writer)
            score = content.find("div",class_="star clearfix").find("span",class_="rating_nums").string
            # print(score)
            countTemp = content.find("div",class_="star clearfix").find("span",class_="pl").string
            count = countTemp[1:len(countTemp)-1].strip()
            record = title+writer+price+score+count+"\n"
            print(record)
            file.write(record)

结果示例:

top250图片.png

说明:BeautifulSoup通过标签来定位解析属性值,通常需要开发者在浏览器调式模式中(F12)查看各级结构,逐步定位。把以上三段信息合在一起即是完整的程序,故不再提供完整的代码下载地址。

上一篇下一篇

猜你喜欢

热点阅读