python使用bs4获取58同城城市分类的方法

本文实例讲述了python使用bs4获取58同城城市分类的方法。分享给大家供大家参考。具体如下:

# -*- coding:utf-8 -*-
#! /usr/bin/python
import urllib
import os, datetime, sys
from bs4 import beautifulsoup
reload(sys)
sys.setdefaultencoding( “utf-8” )
__baseurl__ = “http://bj.58.com/”
__initurl__ = “http://bj.58.com/hezu/”
soup=beautifulsoup(urllib.urlopen(__initurl__))
lv1elements = soup.html.body.section.find(‘p’, ‘relative’).find(‘dl’, ‘secitem’)(‘a’,href=true)
f=open(‘data.txt’, ‘w’)
for element in lv1elements[1:]:
f.write((element.get_text() + ‘\r\n’))
print element.get_text()
url = __baseurl__ + element.get(‘href’)
print url
soup=beautifulsoup(urllib.urlopen(url))
lv2elements = soup.html.body.section.find(‘p’, ‘relative’).find(‘dl’, ‘secitem’).find(‘p’, ‘subarea’).find_all(‘a’)
texts = [t.get_text() for t in lv2elements]
f.write(‘ ‘.join(texts) + ‘\r\n\r\n’)
f.close()

希望本文所述对大家的python程序设计有所帮助。

Posted in 未分类

发表评论