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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

Python多进程库multiprocessing中进程池Pool类的使用详解

Python多进程库multiprocessing中进程池Pool类的使用详解

问题起因 最近要将一个文本分割成好几个topic,每个topic设计一个regressor,各regressor是相互独立的,最后汇总所有topic的regressor得到总得预测结果。...

使用CodeMirror实现Python3在线编辑器的示例代码

使用CodeMirror实现Python3在线编辑器的示例代码

一、编写页面 主要是引入相关的css文件和js文件,这里采用简单插入link和script标签的形式。 <!DOCTYPE html> <html lang="en...

python base64 decode incorrect padding错误解决方法

python的base64.decodestring方法做base64解码时报错: 复制代码 代码如下: Traceback (most recent call last):  ...

python selenium登录豆瓣网过程解析

登录流程: 实例化一个driver,然后driver.get()发送请求 最重要的:切换iframe子框架,因为豆瓣的网页中的登录那部分是一个ifrme,必须切换才能寻找到对...

python基础教程之字典操作详解

字典dictionary 1.键值对的集合(map) 2.字典是以大括号“{}”包围的数据集合 3.字典是无序的,在字典中通过键来访问成员。 可变的,可嵌套,可以原处修改扩展等,不产生新...