找回密码
 立即注册
首页 资源区 代码 爬虫方式(模拟用户)

爬虫方式(模拟用户)

赴忽 3 天前
基于rake的爬取代码
  1. require 'nokogiri'
  2. require 'json'
  3. require 'open-uri'
  4. namespace :spider_sbi_code_info do
  5.   task table_data: :environment do
  6.     options = Selenium::WebDriver::Chrome::Options.new
  7.     options.add_argument('--headless') # 无头模式,不显示浏览器界面
  8.     driver = Selenium::WebDriver.for :chrome, options: options
  9.     csv_filename_list = ["table_data_0_普通株式.csv", "table_data_1_米国ETF.csv", "table_data_2_各国ADR.csv"]
  10.     begin
  11.       # 初始化文件
  12.       csv_filename_list.each do |file|
  13.         if File.exist?("db/csv/#{file}")
  14.           File.delete("db/csv/#{file}")
  15.           p "删除已存在的文件 #{file}"
  16.         end
  17.       end
  18.       # 访问目标网站
  19.       url = 'https://search.sbisec.co.jp/v2/popwin/info/stock/pop6040_usequity_list.html'
  20.       driver.get(url)
  21.       dropdowns = driver.find_elements(css: '.form-control.input-sm')
  22.       # 遍历每个下拉列表并选择选项为 "-1"
  23.       dropdowns.each do |dropdown|
  24.         if dropdown.tag_name == 'select'
  25.           # 初始化 Select 对象
  26.           select = Selenium::WebDriver::Support::Select.new(dropdown)
  27.           # 通过 value 属性选择选项为 "-1"
  28.           select.select_by(:value, '-1')
  29.         end
  30.       end
  31.       # 等待页面加载完全
  32.       wait = Selenium::WebDriver::Wait.new(timeout: 10)
  33.       wait.until { driver.execute_script('return document.readyState') == 'complete' }
  34.       # 获取页面内容
  35.       html_content = driver.page_source
  36.       doc = Nokogiri::HTML(html_content)
  37.       tables = doc.css('.foo_table, div.accTbl01 > table[summary="layout"]')
  38.       if tables.any?
  39.         # 提取表格数据并写入 CSV 文件
  40.         tables.each_with_index do |table, index|
  41.           # 提取表格数据
  42.           table_data = table.css('tr').reject do |row|
  43.             index > 2 && row.css('th, td').map(&:text) == ["ティッカー", "銘柄(英語)", "事業内容", "市場"]
  44.           end.map { |row| row.css('th, td').map { |cell| cell.text.gsub("\n", '') } }
  45.           # 确定 CSV 文件名
  46.           csv_filename = if index > 2
  47.                            "db/csv/#{csv_filename_list.last}"
  48.                          else
  49.                            "db/csv/#{csv_filename_list[index]}"
  50.                          end
  51.           # 写入 CSV 文件
  52.           CSV.open(csv_filename, 'a') do |csv|
  53.             table_data.each { |row| csv << row }
  54.           end
  55.           p "存入数据到 #{csv_filename}"
  56.         end
  57.       else
  58.         p "没有找到表格"
  59.       end
  60.       title = "SBI証券取扱銘柄リスト一覧の送付_#{Date.today.strftime('%Y/%m/%d')}"
  61.       content = "関係者各位<br>お疲れ様です。<br>SBI証券のサイトより、取扱銘柄一覧をスクレイピングしましたので、<br>メールにて送付させて頂きました。<br>スクレイピング先のURL:<br>https://search.sbisec.co.jp/v2/popwin/info/stock/pop6040_usequity_list.html<br><br>ご確認をお願い致します。"
  62.       attachments = csv_filename_list.map { |filename| File.join('db/csv', filename) }
  63.       ExtMail.send_mail(title: title, body: content, template_name: 'system_mail', attachments: attachments, to: Yml::MAIL[:spider_sbi_stocks][Rails.env])
  64.       csv_filename_list.each do |file|
  65.         if File.exist?("db/csv/#{file}")
  66.           File.delete("db/csv/#{file}")
  67.           p "删除已存在的文件 #{file}"
  68.         end
  69.       end
  70.     rescue Exception => e
  71.       p "发生错误: #{e.message}"
  72.     ensure
  73.       driver.quit if driver
  74.     end
  75.   end
  76. end
复制代码
  1.   options = Selenium::WebDriver::Chrome::Options.new
  2.   options.add_argument('--headless') # 无头模式,不显示浏览器界面
  3.   driver = Selenium::WebDriver.for :chrome, options: options
复制代码
配置并启动 Selenium WebDriver:

  • Selenium::WebDriver::Chrome::Options.new 创建一个 Chrome 浏览器的选项实例。
  • options.add_argument('--headless') 添加一个选项,使浏览器以无头模式运行(不显示界面)。
  • Selenium::WebDriver.for :chrome, options: options 启动 Chrome 浏览器并应用这些选项。
  1. dropdowns = driver.find_elements(css: '.form-control.input-sm')
复制代码
找到页面上的所有下拉列表元素:

  • driver.find_elements(css: '.form-control.input-sm') 使用 CSS 选择器找到页面上所有具有 form-control input-sm 类的元素。
  1. dropdowns.each do |dropdown|
  2.         if dropdown.tag_name == 'select'
  3.           select = Selenium::WebDriver::Support::Select.new(dropdown)
  4.           select.select_by(:value, '-1')
  5.         end
  6.       end
复制代码
遍历每个找到的下拉列表,并选择值为 -1 的选项:

  • dropdowns.each do |dropdown| 迭代每个下拉列表。
  • if dropdown.tag_name == 'select' 检查元素是否是 select 标签。
  • select = Selenium::WebDriver::Support::Select.new(dropdown) 创建一个新的 Select 对象。
  • select.select_by(:value, '-1') 通过 value 属性选择值为 -1 的选项。
  1. wait = Selenium::WebDriver::Wait.new(timeout: 10)
  2. wait.until { driver.execute_script('return document.readyState') == 'complete' }
复制代码
等待页面完全加载:

  • wait = Selenium::WebDriver::Wait.new(timeout: 10) 创建一个新的 Wait 对象,设置超时时间为 10 秒。
  • wait.until { driver.execute_script('return document.readyState') == 'complete' } 等待页面的 readyState 变为 complete,表示页面加载完成。
  1. html_content = driver.page_source
  2. doc = Nokogiri::HTML(html_content)
复制代码
这段代码获取页面内容并使用 Nokogiri 解析:

  • html_content = driver.page_source 获取当前页面的 HTML 源代码。
  • doc = Nokogiri::HTML(html_content) 使用 Nokogiri 解析 HTML 内容,创建一个文档对象。
  1. tables = doc.css('.foo_table, div.accTbl01 > table[summary="layout"]')
复制代码
这行代码使用 CSS 选择器找到页面上的特定表格:

  • tables = doc.css('.foo_table, div.accTbl01 > table[summary="layout"]') 找到具有特定 CSS 类和属性的表格元素

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册