selenium的安装与使用
selenium是一个浏览器自动化测试工具,用它可以模拟浏览器点击等操作
pip install selenium
接下来以Chrome为例,需要下载浏览器的web driver,才能进行使用。
在这个镜像网站上可以下载chrome driver,可以查看自己当前的浏览器版本下载对应的driver,并放到和你代码同一级目录下。
关于其他selenium的介绍和方法可以参考博客:python爬虫从入门到放弃(八)之 Selenium库的使用,里面有详细的讲解,这里不多说。
关于下拉选择框的选择方法:selenium下拉选择。
网站的抓取
我们要爬取的是http://www.fromtexttospeech.com/的网站,输入某种文字后选择语言、发音人等可以生成语音,并提供下载链接下载该段语音的mp3。我们要做的就是输入我们的语料并把每一段MP3文件下载保存下来。
但是这是国外的网站,加载很慢,而selenium的操作必须等网站加载完毕了才会进行,因此速度就很慢。因此selenium提供了一些选项改变网站加载策略,让你的操作可以在整个网站加载未完成前就进行。
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
desired = DesiredCapabilities.CHROME
desired["pageLoadStrategy"] = "none"
但这样会会使你查找网站元素的时候,网站未加载出来抛出NoSuchElementException。我们可以使用WebDriverWait这个类来进行显式等待。
from selenium.webdriver.support.ui import WebDriverWait
wait = WebDriverWait(browser, 10)
这样可以等待10秒钟,默认每隔0.5调用until、not_until等方法寻找网站元素。如果超时则会抛出TimeoutException。
pyautogui 和 pyperclip
由于要模拟右键点击另存为,并且给文件重命名,所以需要模拟键盘录入,复制、粘贴等动作。
模拟键盘录入使用的是pyautogui的包。它可以可以用程序自动控制鼠标和键盘操作,利用它可以实现自动化任务。简介和使用方法参照这里。
pyperclip提供了复制粘贴等操作。
import pyperclip
pyperclip.copy('Hello world!')
pyperclip.paste()
代码实例
后面是我自己写的简单代码,爬取西班牙语男发音的音频MP3,做了一些异常处理,并且可以断点(从失败的单词重新爬),只要改变传入的数组就好了。但是这个方法还有有些不稳定,在重命名那里有时候会翻车。需要注意的是在爬的时候,电脑不能乱动。
from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
import time
import pyautogui
import pyperclip
# read file
# with open('es-zh.txt', encoding='utf-8')as r:
# text = r.readlines()
# es_words_list = []
# for each in text:
# es_word = each.split('|||')[0].strip()
# es_words_list.append(es_word)
# print(es_words_list[228184])
# print(len(es_words_list))
# with open('es.txt', 'a', encoding='utf-8')as w:
# for each in es_words_list:
# w.write(each + '\n')
with open('es.txt', encoding='utf-8')as r:
es_word_list = r.readlines()
desired = DesiredCapabilities.CHROME
desired["pageLoadStrategy"] = "none"
browser = webdriver.Chrome()
url = 'http://www.fromtexttospeech.com'
browser.get(url)
wait = WebDriverWait(browser, 10)
# spider
def audio_spider(word_list):
count = 1
for each in word_list:
print('正在下载第' + str(count) + '个MP3……' + '共' + str(len(word_list)) + '段……')
print(each)
each = each.strip()
if '/' in each:
each = each.replace('/', ' ')
pyperclip.copy(each)
try:
wait.until(lambda x: x.find_element_by_id('input_text')).clear()
wait.until(lambda x: x.find_element_by_id('input_text')).send_keys(each)
# input_sents = browser.find_element_by_id('input_text')
# input_sents.clear()
# input_sents.send_keys(each)
# 选择语言
select_lang = browser.find_element_by_id('language')
Select(select_lang).select_by_value('Spanish')
# 选择发音人
select_voice = browser.find_element_by_id('voice')
Select(select_voice).select_by_value('IVONA Enrique22 (Spanish [Modern])')
# 点击按钮,跳转
btn = browser.find_element_by_id('create_audio_file')
btn.click()
# 右键
action = ActionChains(browser)
download = wait.until(lambda x: x.find_element_by_xpath("//a[text()='Download audio file']"))
action.context_click(download).perform()
time.sleep(3)
pyautogui.typewrite(['down', 'down', 'down', 'down', 'enter'])
time.sleep(4)
# pyautogui.typewrite([i for i in each])
pyautogui.hotkey('ctrl', 'v')
time.sleep(2)
pyautogui.typewrite(['enter'])
# pyautogui.typewrite(['enter'])
time.sleep(2)
browser.get(url)
count += 1
except NoSuchElementException:
print('第' + str(count) + '个MP3下载失败,从此处重新下载……')
print('no find element')
browser.get(url)
audio_spider(word_list[count - 1:])
except TimeoutException:
print('第' + str(count) + '个MP3下载失败,从此处重新下载……')
print('time out')
browser.get(url)
audio_spider(word_list[count-1:])
audio_spider(es_word_list[10087: 20000])