python爬去知乎和简书内容

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

 一、爬取知乎热门内容

# -*- 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

<
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的scrapy知乎热门话题的案例: 首先,需要安装scrapy和其他需要的库: ``` pip install scrapy pip install requests pip install scrapy-splash ``` 然后,创建一个新的scrapy项目: ``` scrapy startproject zhihu cd zhihu ``` 接着,在`settings.py`中添加一些配置: ```python BOT_NAME = 'zhihu' SPIDER_MODULES = ['zhihu.spiders'] NEWSPIDER_MODULE = 'zhihu.spiders' ROBOTSTXT_OBEY = False DOWNLOAD_DELAY = 3 DOWNLOADER_MIDDLEWARES = { 'scrapy_splash.SplashCookiesMiddleware': 723, 'scrapy_splash.SplashMiddleware': 725, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810, } SPLASH_URL = 'http://localhost:8050' DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter' HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage' ``` 在这里,我们使用了Splash来渲染网页,因此需要添加一些相关的配置。`DOWNLOAD_DELAY`是下载延迟时间,为了避免被网站封禁,最好设置一个较长的时间。 接下来,创建一个名为`zhihu_spider.py`的Spider类: ```python import scrapy from scrapy_splash import SplashRequest class ZhihuSpider(scrapy.Spider): name = 'zhihu' allowed_domains = ['www.zhihu.com'] start_urls = ['https://www.zhihu.com/hot'] script = ''' function main(splash, args) assert(splash:go(args.url)) assert(splash:wait(2)) return splash:html() end ''' def start_requests(self): for url in self.start_urls: yield SplashRequest(url, self.parse, endpoint='execute', args={ 'lua_source': self.script }) def parse(self, response): for item in response.css('.HotItem'): yield { 'title': item.css('.HotItem-title a::text').get(), 'link': item.css('.HotItem-title a::attr(href)').get(), } ``` 在这里,我们使用了SplashRequest来请求页面,并使用Lua脚本来等待页面加载完毕。然后,我们使用CSS选择器来提取热门话题的标题和链接,并将它们存储在字典中,然后使用yield返回。 最后,运行爬虫: ``` scrapy crawl zhihu -o zhihu.csv ``` 这将抓取知乎热门话题的标题和链接,并将它们存储在CSV文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值