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

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

解决出现Incorrect integer value: '' for column 'id' at row 1的问题

解决出现Incorrect integer value: '' for column 'id' at row 1的问题 前言: 今天在学习Python的过程中操作数据库,遇到了一个问题,...

python 扩展print打印文件路径和当前时间信息的实例代码

pinrt函数我们经常使用,但是有时候python自带的print函数打印的信息不够详细,我们可以扩展一下,打印更多的信息,例如程序文件绝对路径、当前日期时间、消息等等。这里我参考了yd...

通过实例学习Python Excel操作

通过实例学习Python Excel操作

这篇文章主要介绍了通过实例学习Python Excel操作,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.python 读取Exc...

Python嵌套列表转一维的方法(压平嵌套列表)

前一段去云英面试,技术官很”不厚道“了问了一个非常简单的问题:如何将多维列表转化了一维的?当时虽然想到了使用迭代或者列表生成式可以做到,但是可以没能可行的代码,回来后一顿后悔。 对于规范...

linux系统使用python监测网络接口获取网络的输入输出

linux系统使用python监测网络接口获取网络的输入输出

net.py 获取网络接口的输入和输出 复制代码 代码如下:#!/usr/bin/env Pythonimport timeimport sys if len(sys.argv) >...