python爬虫-豆瓣爬取数据保存为html文件
2017-11-09 17:41
246 查看
接《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文件:
脚本修改如下:
# -*-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文件:
相关文章推荐
- Python爬虫(入门+进阶)学习笔记 1-5 使用pandas保存豆瓣短评数据
- Python爬虫实战(4):豆瓣小组话题数据采集―动态网页
- python爬虫由浅入深9---定向爬取股票数据信息并保存至本地文件
- python python 入门学习之网页数据爬虫cnbeta文章保存
- Python爬虫(四)——豆瓣数据模型训练与检测
- Python爬虫系列(七)豆瓣图书排行榜(数据存入到数据库)
- 第三百四十二节,Python分布式爬虫打造搜索引擎Scrapy精讲—爬虫数据保存
- Python爬虫实战(4):豆瓣小组话题数据采集—动态网页
- Python3 爬虫拉勾网抓取数据保存在Excel中
- python3爬虫爬取豆瓣电影并保存到sql serve数据库
- Python3爬虫从入门到自残(三):保存数据
- 人生苦短,我用Python--爬虫模拟登陆教务处并且保存数据到本地
- Python爬虫-利用百度地图API接口爬取数据并保存至MySQL数据库
- python 爬虫 保存豆瓣TOP250电影海报及修改名称
- Python爬虫抓取豆瓣商业书籍,并保存为txt便于查阅
- python爬虫知识点三--解析豆瓣top250数据
- python爬虫数据保存到本地各种格式的方法
- python selenium爬虫实践:获取自如租房数据保存到文件
- (8)Python爬虫——爬取豆瓣影评数据
- Python爬虫入门2 | 爬取豆瓣电影信息