用selenium实现一个简单爬虫,下载网站文件

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])

使用Java设计一个爬虫爬取豆瓣评论信息的话,可以按照以下步骤进行: 1. 首先,需要选择一个网络爬虫框架,比较常用的有Jsoup、HttpClient、Selenium等,这里以Jsoup为例。 2. 然后,需要确定需要爬取的页面和其对应的URL。以豆瓣电影评论页面为例,URL可以是:https://movie.douban.com/subject/电影ID/comments?start=0&limit=20&sort=new_score&status=P 3. 根据URL,使用Jsoup发送HTTP请求,获取网页源代码。 4. 使用Jsoup解析网页源代码,获取需要的数据。比如,可以使用CSS选择器或正则表达式来获取评论内容、评分、用户名等信息。 5. 如果需要爬取多页数据,可以通过循环改变URL中的start参数来获取多页数据。 6. 最后,将获取的数据保存到数据库或者文件中。 下面是一个简单的示例代码,用于获取豆瓣电影《肖申克的救赎》的前20条评论: ```java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; public class DoubanSpider { public static void main(String[] args) throws IOException { String url = "https://movie.douban.com/subject/1292052/comments?start=0&limit=20&sort=new_score&status=P"; Document document = Jsoup.connect(url).get(); Elements elements = document.select("div.comment-item"); for (Element element : elements) { String username = element.select("a").first().text(); String rating = element.select("span.rating").attr("title"); String content = element.select("span.short").text(); System.out.println("用户名:" + username); System.out.println("评分:" + rating); System.out.println("评论内容:" + content); System.out.println("---------------------------"); } } } ``` 以上代码中,我们使用Jsoup连接到豆瓣电影《肖申克的救赎》的评论页面,然后使用CSS选择器获取每个评论的用户名、评分和评论内容,并将其输出到控制台。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值