ruby+nokogori抓取糗事百科前10页并存储进数据库示例
程序员文章站
2022-06-25 09:55:22
ruby,nokogori,爬取糗事百科最新的10页加图片比并同时保存进文本跟数据库
复制代码 代码如下:#encoding:utf-8require "open-uri...
ruby,nokogori,爬取糗事百科最新的10页加图片比并同时保存进文本跟数据库
复制代码 代码如下:
#encoding:utf-8
require "open-uri"
require "nokogiri"
require "mysql"
@dbh=mysql.real_connect("localhost","root","dengli","pachong")
@file=open("qb.txt","w")
def getqiubai(url)
data=open(url){|f| f.read}
doc=nokogiri::html(data)
doc.css('div.block.untagged.mb15.bs2').each{|p|
content=p.css('div.content').text
@file.puts("#{content}\n")
img=p.css('div.thumb img').each{|img|
imgaddr=img.attr('src')
@file.puts("#{imgaddr}\n")
time=time.now
sql="insert into qiushibaike (`body`,`img`,`time`) values ('#{content}','#{imgaddr}','#{time}')"
@dbh.query(sql)
}
}
end
for i in 1..10
@file.puts("这是第#{i}页")
url="http://www.qiushibaike.com/8hr/page/#{i}"
getqiubai(url)
end