Python使用bs4獲取58同城城市分類的方法
更新時間:2015年07月08日 12:05:50 作者:小剛1
這篇文章主要介紹了Python使用bs4獲取58同城城市分類的方法,涉及Python使用BeautifulSoup庫解析html頁面的技巧,需要的朋友可以參考下
本文實例講述了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('div', '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('div', 'relative').find('dl', 'secitem').find('div', 'subarea').find_all('a')
texts = [t.get_text() for t in lv2Elements]
f.write(' '.join(texts) + '\r\n\r\n')
f.close()
希望本文所述對大家的Python程序設計有所幫助。
相關文章
Pandas實現dataframe和np.array的相互轉換
今天小編就為大家分享一篇Pandas實現dataframe和np.array的相互轉換,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

