Python-网络爬虫之BeautifulSoup

在上一节记录了如何使用urllib进行网络爬虫,并将数据存储。但是我当时是使用的正则表达式进行的数据过滤,有些不全面。接下来我将记录一种更加方便的解析数据的操作–BeautifulSoup:

安装beautifulsoup4

在这里插入图片描述

导包
import urllib.request
from bs4 import BeautifulSoup
代码实现
#coding:utf-8
import urllib.request
from bs4 import BeautifulSoup


class Reptile(object):

    def start(self):
        pageCount = 10;
        currentPage = 1;
        while currentPage <= pageCount:
            url = "http://www.neihan.net/text_%d.html"%currentPage
            send_headers = {
                "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
            }
            print("开始爬取第%d页的数据..." % currentPage)
            file = urllib.request.Request(url,headers=send_headers)
            html = urllib.request.urlopen(file).read().decode("utf-8")
            info = BeautifulSoup(html,"html.parser")
            # 匹配所有<dd class="content">的标签
            contents = info.find_all("dd", {"class": "content"})
            self.writeToFile(contents)
            print("爬取第%d页的数据完毕"%currentPage)
            currentPage+=1

    def writeToFile(self,list):
        for temp in list:
            file = open("段子.txt","a")
            # 获取标签的内容
            file.write(temp.get_text())
            file.write("\n\n")
            file.close()



if __name__ == "__main__":
    reptile = Reptile()
    reptile.start()
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值