爬虫初学,写个简单的爬虫

首先构造一下请求头,调用request模块发送请求,

def request_data(url):
    headers = {
        'User-Agent': 'Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome /70.0.3538.102Safari/537.36Edge/18.18362'
    }
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.content.decode('gbk', 'ignore')
    except requests.RequestException:
        return None

然后用bs4解析一下我们的html网页,

soup = BeautifulSoup(html, 'lxml')

找一下我们前端网页中我们需要的数据的所在标签,获取一下

def get_item(soup):
    list = soup.find(class_='listbox').find_all('li')
    for item in list:

        item_name = item.find('a').string
        if item_name is not None:

            write_item(item_name)

写入,

def write_item(item):

    print('开始写入数据 =======>' + str(item))
    with open('56.txt', 'a', encoding='utf-8') as f:
        f.write(item+'\n')
        f.close()
def main(page):
    url = 'http://www.zhongyoo.com/fangji/page_'+str(page)+'.html'
    html = request_data(url)

    soup = BeautifulSoup(html, 'lxml')
    get_item(soup)

一个简单的小爬虫就搞定了,看下结果

开始写入数据 =======>定喘汤
开始写入数据 =======>射干麻黄汤
开始写入数据 =======>黛蛤散
开始写入数据 =======>二母散
开始写入数据 =======>贝母瓜蒌散
开始写入数据 =======>清燥救肺汤
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值