python爬虫-豆瓣爬取数据保存为html文件

python爬虫-豆瓣数据爬取-正则匹配中的案例五,将爬取的豆瓣租房信息网址和标题保存为html文件。

脚本修改如下:

 

# -*-coding:utf-8 -*-  
import requests  
import re  
from bs4 import BeautifulSoup  
  
#直接用正则表达式找出链接中包含https://www.douban.com/group/topic/的所有链接,即为发布的所有租房信息  
r=requests.get("https://www.douban.com/group/futianzufang/")  
# print r.text  
soup=BeautifulSoup(r.text,'html.parser')  
print '获取链接中包含https://www.douban.com/group/topic/的所有链接'  
links=soup.find_all('a',href=re.compile(r"https://www.douban.com/group/topic/"))  
n=0
res_data={}

fout=open('output.html','w')  
fout.write("<html>")#设置输出的html文件的格式
fout.write("<body>")
fout.write("<table>")

for link in links:
    print link.name,link['href'],link.get_text()
    
    res_data['url']=link['href']#将租房链接赋值给res_data的url
    res_data['content']=link.get_text()  #将租房标题赋值给res_data的content
    
    fout.write("<tr>")
    fout.write("<td>%s</td>"% res_data['url'])          #将爬取的租房链接写入到html文件中 
    fout.write("<td>%s</td>"% res_data['content'].encode('utf-8'))  #将爬取的租房标题写入到html文件中 
    fout.write("</tr>")
    n+=1
print '共发布了%d条租房信息'%n    
        
fout.write("</table>")
fout.write("</body>")
fout.write("</html>")
   


查看output.html文件:

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值