python爬去知乎和简书内容

本文介绍了如何使用Python进行网络爬虫,涵盖了从爬取知乎热门内容到利用Scrapy框架抓取简书信息的全过程,重点讨论了bs4库和selenium在爬虫中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 一、爬取知乎热门内容

# -*- coding: utf-8-*-
import urllib2
import re
from BeautifulSoup import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf8')

f = open('howtoTucao2.txt', 'w')  # open the file

for pagenum in range(1, 21):

    strpagenum = str(pagenum)
    print "Getting data for Page " + strpagenum  # for we can see the process in shell
    url = "http://www.zhihu.com/collection/27109279?page=" + strpagenum
    page = urllib2.urlopen(url)  # get the web page
    soup = BeautifulSoup(page)  # use BeautifulSoup to parsing the web page

    ALL = soup.findAll(attrs={'class': ['zm-item-title', 'content hidden']})

    for each in ALL:
        if each.name == 'h2':
            nowstring = re.sub('<s.+>\n<a.+>\n<.+>\n', '', each.a.string)
            nowstring = re.sub('<br>', '\n', nowstring)
            nowstring = re.sub('<\w+>', '', nowstring)
            nowstring = re.sub('</\w+>', '', nowstring)
            nowstring = re.sub('<.+>', '\n图片\n', nowstring)
            nowstring = re.sub('"', '"', nowstring)
            print nowstring
            if nowstring:
                f.write(nowstring)
            else:
                f.write("\n No Answer \n")
        else:
            nowstring = re.sub('<s.+>\n<a.+>\n<.+>\n', '', each.string)
            nowstring = re.sub('<br>', '\n', nowstring)
            nowstring = re.sub('<\w+>', '', nowstring)
            nowstring = re.sub('</\w+>', '', nowstring)
            nowstring = re.sub('<.+>', '\n图片\n', nowstring)
            nowstring = re.sub('"', '"', nowstring)
            print nowstring
            if nowstring:
                f.write(nowstring)
            else:
                f.write("\n No Answer \n")
f.close()  # close the file


二、爬取简书内容(基于Scrapy框架)

 (1)item.py

# -*- coding: utf-8 -*-

# Define here the models for your
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值