1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 将爬虫数据转换成html python爬虫-豆瓣爬取数据保存为html文件

将爬虫数据转换成html python爬虫-豆瓣爬取数据保存为html文件

时间:2021-03-20 10:27:10

相关推荐

将爬虫数据转换成html python爬虫-豆瓣爬取数据保存为html文件

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

脚本修改如下:

# -*-coding:utf-8 -*-

import requests

import re

from bs4 import BeautifulSoup

#直接用正则表达式找出链接中包含/group/topic/的所有链接,即为发布的所有租房信息

r=requests.get("/group/futianzufang/")

# print r.text

soup=BeautifulSoup(r.text,'html.parser')

print '获取链接中包含/group/topic/的所有链接'

links=soup.find_all('a',href=pile(r"/group/topic/"))

n=0

res_data={}

fout=open('output.html','w')

fout.write("")#设置输出的html文件的格式

fout.write("

")

fout.write("

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("

")

fout.write("

%s"% res_data['url']) #将爬取的租房链接写入到html文件中

fout.write("

%s"% res_data['content'].encode('utf-8')) #将爬取的租房标题写入到html文件中

fout.write("

")

n+=1

print '共发布了%d条租房信息'%n

fout.write("

")

fout.write("")

fout.write("")

查看output.html文件:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。