基于selenium的小说爬取

以  https://www.beqege.cc 为目标

爬取的是 小说《死人经》

from selenium.webdriver import Chrome#实例化对象
from selenium.webdriver import ChromeOptions#实例化对象
from selenium.webdriver.common.by import By#定位元素
from lxml import etree
import time


options = ChromeOptions()
options.add_experimental_option('detach', True) #避免因程序运行完或报错导致浏览器自动关闭
driver = Chrome(options=options)
driver.get(r'https://www.beqege.cc/32073/')


def get_text(link):
    subdriver = Chrome()
    js = f'window.open("{link}")'
    subdriver.execute_script(js)
    handles = subdriver.window_handles
    subdriver.switch_to.window(handles[-1])
    time.sleep(1)
    tree = etree.HTML(subdriver.page_source)
    ps = tree.xpath('//*[@id="content"]/p')
    for p in ps:
        try:
            text = p.xpath('.//text()')[0]
            time.sleep(0.5)
            with open(title, 'a', encoding='utf8') as fp:
                fp.write(text)
                fp.write("\n")
        except:
            pass
    subdriver.close()


tree=etree.HTML(driver.page_source)
dds=tree.xpath('//*[@id="list"]//dd')
for dd in dds:
    text=dd.xpath('.//text()')[0]
    href=dd.xpath('./a/@href')[0]
    title=f'./小说/死人经/{text}.txt'
    link=f'https://www.beqege.cc{href}'
    get_text(link)

driver.quit()




  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值