以前写的一个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/