Python爬虫系列(二)Quotes to Scrape(谚语网站的爬取实战)

接下来自己会写一些关于爬虫 实战的内容,把所学的知识加以运用。这篇文章是关于一个英文谚语网站的谚语爬取,并输出结果。

这个网站大致有10页谚语,所以是一个关于selenium使用的例子,大致思路使用webrdriver获取“下一页”按钮,获取每一页源码,输入所要的谚语

使用到的模块或工具(这些要提前准备好):

1、 BeautifulSoup

2、selenium 

3、time

4、driver=webdriver.Chrome("G:/chromedriver/chromedriver.exe")(我使用的Chrome驱       动, PhantomJS也可以)

(ps:初期学习爬虫的拾遗与总结这里有介绍)

目标网站:Quotes to Scrape

Python爬虫系列(二)Quotes to Scrape(谚语网站的爬取实战)_第1张图片
目标网站

1、打开Chrom的开发者工具,找到谚语所在的位置

Python爬虫系列(二)Quotes to Scrape(谚语网站的爬取实战)_第2张图片
谚语所在位置

2、找到下一页按钮Next

Python爬虫系列(二)Quotes to Scrape(谚语网站的爬取实战)_第3张图片
next按钮

3、把所要提取谚语的位置和下一页按钮位置确定之后,下面所写的代码:

加了详细备注,看起来应该不算困难

#xpath和自动化的结合使用

#from lxml import etree

from bs4 import BeautifulSoup

from selenium import webdriver

import time

#加载驱动

driver=webdriver.Chrome("G:/chromedriver/chromedriver.exe")

#driver = webdriver.PhantomJS()#这个我没试

#打开目标网址并获取源码

driver.get('http://quotes.toscrape.com/')

soup=BeautifulSoup(driver.page_source,'lxml')

i=0

while True:

try:

#找到并获取第一页的谚语位置span集合:items,点击下一页之后会变成下一页的谚语集合

items=soup.find_all('span',class_='text')

#打印获取到第一页的谚语

for item in items:

print('谚语'+str(i)+':')

print(item.text)

i+=1

#获取下一页next按钮

elem=driver.find_element_by_xpath('//ul[@class="pager"]/li[@class="next"]/a')

elem.click()

#停顿2秒,页面观察点击下一页的效果

time.sleep(2)

#获取下一页源码

soup=BeautifulSoup(driver.page_source,'lxml')

except:

break

4、下面是结果:

结果图

你可能感兴趣的:(Python爬虫系列(二)Quotes to Scrape(谚语网站的爬取实战))