前言

首先,分析来爬虫的思路:先在第一个网页(https://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0)中得到500个名人所在的网址,接下来就爬取这500个网页中的名人的名字及描述,如无描述,则跳过。接下来,我们将介绍实现这个爬虫的4种方法,并分析它们各自的优缺点,希望能让读者对爬虫有更多的体会。实现爬虫的方法为:一般方法(同步,requests+BeautifulSoup)

并发(使用concurrent.futures模块以及requests+BeautifulSoup)

异步(使用aiohttp+asyncio+requests+BeautifulSoup)

使用框架Scrapy

一般方法

一般方法即为同步方法,主要使用requests+BeautifulSoup,按顺序执行。完整的Python代码如下:

import requests

from bs4 import BeautifulSoup

import time

#python学习群:695185429

# 开始时间

t1 = time.time()

print('#' * 50)

url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0"

# 请求头部

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'}

# 发送HTTP请求

req = requests.get(url, headers=headers)

# 解析网页

soup = BeautifulSoup(req.text, "lxml")

# 找到name和Description所在的记录

human_list = soup.find(id='mw-whatlinkshere-list')('li')

urls = []

# 获取网址

for human in human_list:

url = human.find('a')['href']

urls.append('https://www.wikidata.org'+url)

# 获取每个网页的name和description

def parser(url):

req = requests.get(url)

# 利用BeautifulSoup将获取到的文本解析成HTML

soup = BeautifulSoup(req.text, "lxml")

# 获取name和description

name = soup.find('span', class_="wikibase-title-label")

desc = soup.find('span', class_="wikibase-descriptionview-text")

if name is not None and desc is not None:

print('%-40s,\t%s'%(name.text, desc.text))

for url in urls:

parser(url)

t2 = time.time() # 结束时间

print('一般方法,总共耗时:%s' % (t2 - t1))

print('#' * 50)

输出的结果如下(省略中间的输出,以……代替):

##################################################

George Washington , first President of the United States

Douglas Adams , British author and humorist (1952–2001)

......

Willoughby Newton , Politician from Virginia, USA

Mack Wilberg , American conductor

一般方法,总共耗时:724.9654655456543

##################################################

使用同步方法,总耗时约725秒,即12分钟多。一般方法虽然思路简单,容易实现,但效率不高,耗时长。那么,使用并发试试看。

并发方法

并发方法使用多线程来加速一般方法,我们使用的并发模块为concurrent.futures模块,设置多线程的个数为20个(实际不一定能达到,视计算机而定)。完整的Python代码如下:

import requests

from bs4 import BeautifulSoup

import time

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED

# 开始时间

t1 = time.time()

print('#' * 50)

url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0"

# 请求头部

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'}

# 发送HTTP请求

req = requests.get(url, headers=headers)

# 解析网页

soup = BeautifulSoup(req.text, "lxml")

# 找到name和Description所在的记录

human_list = soup.find(id='mw-whatlinkshere-list')('li')

urls = []

# 获取网址

for human in human_list:

url = human.find('a')['href']

urls.append('https://www.wikidata.org'+url)

# 获取每个网页的name和description

def parser(url):

req = requests.get(url)

# 利用BeautifulSoup将获取到的文本解析成HTML

soup = BeautifulSoup(req.text, "lxml")

# 获取name和description

name = soup.find('span', class_="wikibase-title-label")

desc = soup.find('span', class_="wikibase-descriptionview-text")

if name is not None and desc is not None:

print('%-40s,\t%s'%(name.text, desc.text))

# 利用并发加速爬取

executor = ThreadPoolExecutor(max_workers=20)

# submit()的参数: 第一个为函数, 之后为该函数的传入参数,允许有多个

future_tasks = [executor.submit(parser, url) for url in urls]

# 等待所有的线程完成,才进入后续的执行

wait(future_tasks, return_when=ALL_COMPLETED)

t2 = time.time() # 结束时间

print('并发方法,总共耗时:%s' % (t2 - t1))

print('#' * 50)

输出的结果如下(省略中间的输出,以……代替):

##################################################

Larry Sanger , American former professor, co-founder of Wikipedia, founder of Citizendium and other projects

Ken Jennings , American game show contestant and writer

......

Antoine de Saint-Exupery , French writer and aviator

Michael Jackson , American singer, songwriter and dancer

并发方法,总共耗时:226.7499692440033

##################################################

使用多线程并发后的爬虫执行时间约为227秒,大概是一般方法的三分之一的时间,速度有了明显的提升啊!多线程在速度上有明显提升,但执行的网页顺序是无序的,在线程的切换上开销也比较大,线程越多,开销越大。

异步方法

异步方法在爬虫中是有效的速度提升手段,使用aiohttp可以异步地处理HTTP请求,使用asyncio可以实现异步IO,需要注意的是,aiohttp只支持3.5.3以后的Python版本。使用异步方法实现该爬虫的完整Python代码如下:

import requests

from bs4 import BeautifulSoup

import time

import aiohttp

import asyncio

# 开始时间

t1 = time.time()

print('#' * 50)

url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0"

# 请求头部

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'}

# 发送HTTP请求

req = requests.get(url, headers=headers)

# 解析网页

soup = BeautifulSoup(req.text, "lxml")

# 找到name和Description所在的记录

human_list = soup.find(id='mw-whatlinkshere-list')('li')

urls = []

# 获取网址

for human in human_list:

url = human.find('a')['href']

urls.append('https://www.wikidata.org'+url)

# 异步HTTP请求

async def fetch(session, url):

async with session.get(url) as response:

return await response.text()

# 解析网页

async def parser(html):

# 利用BeautifulSoup将获取到的文本解析成HTML

soup = BeautifulSoup(html, "lxml")

# 获取name和description

name = soup.find('span', class_="wikibase-title-label")

desc = soup.find('span', class_="wikibase-descriptionview-text")

if name is not None and desc is not None:

print('%-40s,\t%s'%(name.text, desc.text))

# 处理网页,获取name和description

async def download(url):

async with aiohttp.ClientSession() as session:

try:

html = await fetch(session, url)

await parser(html)

except Exception as err:

print(err)

# 利用asyncio模块进行异步IO处理

loop = asyncio.get_event_loop()

tasks = [asyncio.ensure_future(download(url)) for url in urls]

tasks = asyncio.gather(*tasks)

loop.run_until_complete(tasks)

t2 = time.time() # 结束时间

print('使用异步,总共耗时:%s' % (t2 - t1))

print('#' * 50)

输出结果如下(省略中间的输出,以……代替):

##################################################

Frédéric Taddeï , French journalist and TV host

Gabriel Gonzáles Videla , Chilean politician

......

Denmark , sovereign state and Scandinavian country in northern Europe

Usain Bolt , Jamaican sprinter and soccer player

使用异步,总共耗时:126.9002583026886

##################################################

显然,异步方法使用了异步和并发两种提速方法,自然在速度有明显提升,大约为一般方法的六分之一。异步方法虽然效率高,但需要掌握异步编程,这需要学习一段时间。

如果有人觉得127秒的爬虫速度还是慢,可以尝试一下异步代码(与之前的异步代码的区别在于:仅仅使用了正则表达式代替BeautifulSoup来解析网页,以提取网页中的内容):

import requests

from bs4 import BeautifulSoup

import time

import aiohttp

import asyncio

import re

# 开始时间

t1 = time.time()

print('#' * 50)

url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0"

# 请求头部

headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'}

# 发送HTTP请求

req = requests.get(url, headers=headers)

# 解析网页

soup = BeautifulSoup(req.text, "lxml")

# 找到name和Description所在的记录

human_list = soup.find(id='mw-whatlinkshere-list')('li')

urls = []

# 获取网址

for human in human_list:

url = human.find('a')['href']

urls.append('https://www.wikidata.org' + url)

# 异步HTTP请求

async def fetch(session, url):

async with session.get(url) as response:

return await response.text()

# 解析网页

async def parser(html):

# 利用正则表达式解析网页

try:

name = re.findall(r'(.+?)', html)[0]

desc = re.findall(r'(.+?)', html)[0]

print('%-40s,\t%s' % (name, desc))

except Exception as err:

pass

# 处理网页,获取name和description

async def download(url):

async with aiohttp.ClientSession() as session:

try:

html = await fetch(session, url)

await parser(html)

except Exception as err:

print(err)

# 利用asyncio模块进行异步IO处理

loop = asyncio.get_event_loop()

tasks = [asyncio.ensure_future(download(url)) for url in urls]

tasks = asyncio.gather(*tasks)

loop.run_until_complete(tasks)

t2 = time.time() # 结束时间

print('使用异步(正则表达式),总共耗时:%s' % (t2 - t1))

print('#' * 50)

输出的结果如下(省略中间的输出,以……代替):

##################################################

Dejen Gebremeskel , Ethiopian long-distance runner

Erik Kynard , American high jumper

......

Buzz Aldrin , American astronaut

Egon Krenz , former General Secretary of the Socialist Unity Party of East Germany

使用异步(正则表达式),总共耗时:16.521944999694824

##################################################

16.5秒,仅仅为一般方法的43分之一,速度如此之快,令人咋舌

爬虫框架Scrapy

最后,我们使用著名的Python爬虫框架Scrapy来解决这个爬虫。我们创建的爬虫项目为wikiDataScrapy,项目结构如下:

在settings.py中设置“ROBOTSTXT_OBEY = False”. 修改items.py,代码如下:

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

import scrapy

class WikidatascrapyItem(scrapy.Item):

# define the fields for your item here like:

name = scrapy.Field()

desc = scrapy.Field()

然后,在spiders文件夹下新建wikiSpider.py,代码如下:

import scrapy.cmdline

from wikiDataScrapy.items import WikidatascrapyItem

import requests

from bs4 import BeautifulSoup

# 获取请求的500个网址,用requests+BeautifulSoup搞定

def get_urls():

url = "http://www.wikidata.org/w/index.php?title=Special:WhatLinksHere/Q5&limit=500&from=0"

# 请求头部

headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'}

# 发送HTTP请求

req = requests.get(url, headers=headers)

# 解析网页

soup = BeautifulSoup(req.text, "lxml")

# 找到name和Description所在的记录

human_list = soup.find(id='mw-whatlinkshere-list')('li')

urls = []

# 获取网址

for human in human_list:

url = human.find('a')['href']

urls.append('https://www.wikidata.org' + url)

# print(urls)

return urls

# 使用scrapy框架爬取

class bookSpider(scrapy.Spider):

name = 'wikiScrapy' # 爬虫名称

start_urls = get_urls() # 需要爬取的500个网址

def parse(self, response):

item = WikidatascrapyItem()

# name and description

item['name'] = response.css('span.wikibase-title-label').xpath('text()').extract_first()

item['desc'] = response.css('span.wikibase-descriptionview-text').xpath('text()').extract_first()

yield item

# 执行该爬虫,并转化为csv文件

scrapy.cmdline.execute(['scrapy', 'crawl', 'wikiScrapy', '-o', 'wiki.csv', '-t', 'csv'])

输出结果如下(只包含最后的Scrapy信息总结部分):

{'downloader/request_bytes': 166187,

'downloader/request_count': 500,

'downloader/request_method_count/GET': 500,

'downloader/response_bytes': 18988798,

'downloader/response_count': 500,

'downloader/response_status_count/200': 500,

'finish_reason': 'finished',

'finish_time': datetime.datetime(2018, 10, 16, 9, 49, 15, 761487),

'item_scraped_count': 500,

'log_count/DEBUG': 1001,

'log_count/INFO': 8,

'response_received_count': 500,

'scheduler/dequeued': 500,

'scheduler/dequeued/memory': 500,

'scheduler/enqueued': 500,

'scheduler/enqueued/memory': 500,

'start_time': datetime.datetime(2018, 10, 16, 9, 48, 44, 58673)}

可以看到,已成功爬取500个网页,耗时31秒,速度也相当OK。再来看一下生成的wiki.csv文件,它包含了所有的输出的name和description,如下图:

可以看到,输出的CSV文件的列并不是有序的。至于如何解决Scrapy输出的CSV文件有换行的问题

Scrapy来制作爬虫的优势在于它是一个成熟的爬虫框架,支持异步,并发,容错性较好(比如本代码中就没有处理找不到name和description的情形),但如果需要频繁地修改中间件,则还是自己写个爬虫比较好,而且它在速度上没有超过我们自己写的异步爬虫,至于能自动导出CSV文件这个功能,还是相当实在的。

总结

本文内容较多,比较了4种爬虫方法,每种方法都有自己的利弊,已在之前的陈述中给出,当然,在实际的问题中,并不是用的工具或方法越高级就越好,具体问题具体分析嘛~

作者:裸睡的猪

python爬取网站四种姿势_python爬取网站数据四种姿势,你值得拥有~相关推荐

  1. python爬取淘宝商品信息_python爬取淘宝商品信息并加入购物车

    先说一下最终要达到的效果:谷歌浏览器登陆淘宝后,运行python项目,将任意任意淘宝商品的链接传入,并手动选择商品属性,输出其价格与剩余库存,然后选择购买数,自动加入购物车. 在开始爬取淘宝链接之前, ...

  2. python可以爬取的内容有什么_Python爬取视频(其实是一篇福利)过程解析 Python爬虫可以爬取什么...

    如何用python爬取视频网站的数据 如何用python爬取js渲染加载的视频文件不是每个人都有资格说喜欢,也不是每个人都能选择伴你一生! 有哪位大神指导下,有些视频网站上的视频文件是通过 js 加载 ...

  3. python爬取股票大单历史记录_python爬取股票实时数据,python爬虫与股票分析

    内容导航: Q1:怎么学python爬取财经信息 本程序使用Python 2.7.6编写,扩展了Python自带的HTMLParser,自动根据预设的股票代码列表,从Yahoo Finance抓取列表 ...

  4. python中函数参数传递的三种方式_python中函数参数传递的几种方法

    转自  http://www.douban.com/note/13413855/ Python中函数参数的传递是通过"赋值"来传递的.但这条规则只回答了函数参数传递的"战 ...

  5. python如何把ts视频拼接起来_Python爬取网站m3u8视频,将ts解密成mp4,合并成整体视频...

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. 今天群里面有一个小伙伴发了一个链接,出于好奇,点击去看了一下,然后确定试试看. 基本开发环境 ...

  6. python爬虫搜特定内容的论文_python爬取指定微信公众号文章

    python怎么抓取微信阅清晨的阳光比不上你的一缕微笑那么动人,傍晚的彩霞比不上你的一声叹息那么心疼,你的一个个举动,一句句话语都给小编带来无尽的幸福. 抓取微信公众号的文章 一.思路分析 目前所知晓 ...

  7. python实现qq登录腾讯视频_Python爬取腾讯视频评论的思路详解

    一.前提条件 安装了Fiddler了(用于抓包分析) 谷歌或火狐浏览器 如果是谷歌浏览器,还需要给谷歌浏览器安装一个SwitchyOmega插件,用于代理服务器 有Python的编译环境,一般选择Py ...

  8. python爬取网页书籍名称代码_python爬取亚马逊书籍信息代码分享

    我有个需求就是抓取一些简单的书籍信息存储到mysql数据库,例如,封面图片,书名,类型,作者,简历,出版社,语种. 我比较之后,决定在亚马逊来实现我的需求. 我分析网站后发现,亚马逊有个高级搜索的功能 ...

  9. python爬取高考各高校分数线_Python 爬取高校历年分数线

    最近一周一直在帮家里小弟看高考志愿,所以更新的没那么频繁了,请大家见谅. 在看各高校的往年分数时,忍不住手痒,想着能不能给它爬下来?哈哈,说干就干! 1 流程分析 之前无意中在这个网站发现有各个高校的 ...

最新文章

  1. 前端也要学系列:设计模式之装饰者模式
  2. 初学者选黑卡还是微单_入门单反和微单相机该买哪个
  3. linux 运维高级脚本生成器,Linux运维系列,Shell高级脚本自动化编程实战
  4. 第8章4节《MonkeyRunner源码剖析》MonkeyRunner启动运行过程-启动 8
  5. Android安全与逆向之在ubuntu上面搭建NDK环境
  6. 如何修改pfpj的服务器,如何更改布局?
  7. python的request请求401_Python模拟HTTPS请求返回HTTP 401 unauthorized错误
  8. H5实例 移动端页面练习
  9. Mybatis SQL片段
  10. Spring源码分析
  11. love2d 开发环境
  12. payoneer企业账号授权代表验证函怎么写
  13. 【Linux】【Kernel】BUG: scheduling while atomic问题分析
  14. Java的socket简单语法实例以及多线程
  15. 企业上市IPO的必要条件
  16. Linux: Intel Eethernet driver:ixgbe i40e;error “Adapter removed“
  17. linux 强制卸载nfs,linux nfs 卸载
  18. 魔兽模型路径查看更改工具
  19. c4droid中c语言编译器,c4droid怎么安装 c4droid安装教程及使用说明
  20. 山西计算机大赛崔奕,计算机系在华北五省(市、自治区)大学生机器人大赛山西赛区比赛获得佳绩...

热门文章

  1. 计算机组成原理基础题库,计算机组成原理自习题库.docx
  2. 【数据库】【课程设计】商品销售信息管理系统设计
  3. 2022年蓝桥杯:第十三届蓝桥杯大赛软件赛省赛(全部正解做法代码 C/C++ B组)
  4. swoft框架使用笔记
  5. Rust中的引用计数Arc与Rc
  6. c# mysql 连接串_c#数据库连接字符串集合
  7. MYSQL||报错:In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated
  8. 计算机虚拟现实主要学什么,虚拟现实计算机教学应用
  9. python学习(18)--图片分类
  10. EasyUI学习-如何使用jQuery EasyUI?