博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python简单的爬取网页信息并生成json文件与乱码解决小记
阅读量:4588 次
发布时间:2019-06-09

本文共 1515 字,大约阅读时间需要 5 分钟。

以前写的一个Python小程序,以前是放在笔记中的,现搬到这来。

因为Android开发需要一些数据,自己写了一个小小的Python程序来抓取数据。过程可谓一波三折,主要是Python的字符串编码问题,在这记录一下。

直接上代码

# encoding utf-8import urllib2import jsonfrom bs4 import BeautifulSoupdomain = 'http://www.joy.cn/news/'def start_parser(domain_url):    response = urllib2.urlopen(domain_url)    html = response.read()    soup = BeautifulSoup(html)    video_data = {a.get_text(): domain + a.attrs.get('href') for a in soup.select('div.joy_news_div a.joy_item_a')}    return video_datadef get_video_url(video_page_url):    response = urllib2.urlopen(video_page_url)    html = response.read()    soup = BeautifulSoup(html)    video_url = soup.select('div.video source')[0].attrs.get('src')    return video_urldef generate_json_file(domain_url):    url_list = []    page_urls = start_parser(domain_url)    for (k, v) in page_urls.items():        # 如果字符串是这样定义:s=u'中文'        # 则该字符串的编码就被指定为unicode了,即python的内部编码,而与代码文件本身的编码无关。        # 因此,对于这种情况做编码转换,只需要直接使用encode方法将其转换成指定编码即可。        video_data_dict = {'url': get_video_url(v), 'title': k.encode('utf-8')}        url_list.append(video_data_dict)    with open("news_video_urls.json", 'wb') as outfile:        # 存在于list,dict等容器中的unicode字符就是一这种编码方式存在的,单独打印某一项的时候,        # 会显示成中文字符,但是直接打印整个list的时候,就不会做字符映射以正确显示中文        json.dump(url_list, outfile, encoding='utf-8', ensure_ascii=False)if __name__ == '__main__':    generate_json_file(domain + 'all')

 参考链接:http://wuchong.me/blog/2014/04/24/easy-web-scraping-with-python/

转载于:https://www.cnblogs.com/YiloPo/p/5349901.html

你可能感兴趣的文章
2-10
查看>>
CentOS 7 安装 Docker
查看>>
三、MapReduce学习
查看>>
MySQL的表分区详解 - 查看分区数据量,查看全库数据量----转http://blog.csdn.net/xj626852095/article/details/51245844...
查看>>
课程作业02将所有动手动脑的问题以及课后实验问题
查看>>
oracle_(第二课)监听器配置
查看>>
使用xdebug调试程序后程序很慢的原因
查看>>
windows下配置Tomcat7.0.22
查看>>
Perl中命令行参数以及打开管道文件
查看>>
习题 11 提问
查看>>
2018-07-05-Python全栈开发day25-python中的继承
查看>>
MySQL 数据类型(转贴)
查看>>
Maven 常用命令
查看>>
Java注解知识点摘抄
查看>>
决战Leetcode: easy part(1-50)
查看>>
数组中出现次数超过一半的数字
查看>>
图像边缘检测
查看>>
Kill_UiAutomator
查看>>
HDU 2157 How many ways??
查看>>
Floyd最短路径
查看>>