使用selenium爬取小说以及一些注意事项和坑

使用selenium爬取小说

说明:这个网站也可以使用静态方法访问,动态只是练手

目标,使用selenium爬取下面网站中的小说

http://www.xbiquge.la/29/29056/13991590.html?tdsourcetag=s_pctim_aiomsg

的一个小说,并下载到本地磁盘

一,分析网站

  • 1,打开网站,查看一篇文章。获取下一章链接,内容,以及章节名称。

    在这里插入图片描述

  • 2, 分别使用selenium的不同选择方式,进行定位,(当然使用xpath最为简单)

  • 3,xpath的一个小技巧(快速确定路径,最好使用以chrome为内核的浏览器)

在这里插入图片描述

二,开始爬取

  • 代码:

    from selenium import webdriver
    import time
    from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
    
    
    def get_content(url):
        # 使用selenium动态解析网页
        binary = FirefoxBinary(r"E:FireFoxfirefox.exe") # 浏览器位置
        driverPath = r"D:PycharmProjectgeckodriver-v0.26.0-win64geckodriver.exe" # 驱动位置
        # 加载驱动和浏览器
        driver = webdriver.Firefox(executable_path=driverPath, firefox_binary=binary)
        driver.find_elements_by_link_text('下一章')
        driver.get(url=url)
        for i in range(0, 20):
            # 爬取20章
            # 获取每一章名字(使用class选择器)
            name = driver.find_element_by_css_selector('div.bookname').find_element_by_tag_name('h1').text
            # 获取内容(使用id选择器)
            content = driver.find_element_by_id(id_='content')
            text = content.text
            book = {
                'name': name,
                'text': text,
            }
            save_file(book=book)
            # 获取下一页按钮,(使用xpath语法),使用浏览器检查元素
            next_page = driver.find_element_by_xpath('//*[@id="wrapper"]/div[4]/div/div[2]/div[1]/a[4]')
            link = next_page.get_attribute('href')
            driver.get(link)
            time.sleep(1.5)
    
    
    def save_file(book):
        # 保存章节
        text = book['text']
        name = book['name']
        text = text.splitlines()[:-2] # 因为最后两行是广告,去除
        with open('file2/'+name, "w", encoding="utf-8") as f:
            for i in text:
                if i == '':
                    f.write('
    ')
                else:
                    f.write(i)
            print(name+"保存成功!!!!")
    
    
    if __name__ == '__main__':
        url = r"http://www.xbiquge.la/29/29056/13991590.html"
        get_content(url=url)
    
    
    
  • 结果:

在这里插入图片描述

三,注意事项以及selenium的一些坑

  • 1,出现WebDriverException,是因为selenium新版要手动加载浏览器驱动,而驱动下载被墙。下面给出驱动百度网盘下载地址

  • https://pan.baidu.com/s/1yEc1e15HE9r–2oNAOue4A提取码:t4s1

  • 2,如果浏览器没有在注册表中注册,webdriver要手动指定浏览器位置

  • 3,使用find_element_by_link_text获取包含指定文本的标签,之前测试过a标签,但是没有get_attribute()方法(尽量使用xpath或者id,class选择器)

  • 4,跳转页面时,如果时a标签链接的,是不能使用click()方法进行跳转的,必须获取a标签里面的链接,然后使用dirver.get()进行跳转

  • 5,爬虫爬取时要尽量隔一定的时间进行请求,一方面为了不会使目标服务器增加负担,另一方面也是为了使网站反爬虫发现,并且利于webdriver加载网页。

  • 6,pycharm只会部分显示print输出,如果是有大段输出,会除去一部分,往往这样会造成爬取出的结果显示不全,会让人以为爬虫出错。

原文地址:https://www.cnblogs.com/jlxa162hhf/p/14161230.html