使用python BeautifulSoup库抓取58手机维修信息

yipeiwu_com5年前Python爬虫

直接上代码:

复制代码 代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib

import os,datetime,string

import sys

from bs4 import BeautifulSoup

reload(sys)

sys.setdefaultencoding('utf-8')

__BASEURL__ = 'http://bj.58.com/'

__INITURL__ = "http://bj.58.com/shoujiweixiu/"

soup = BeautifulSoup(urllib.urlopen(__INITURL__))

lvlELements = soup.html.body.find('div','selectbarTable').find('tr').find_next_sibling('tr')('a',href=True)

f = open('data1.txt','a')

for element in lvlELements[1:]:

    f.write((element.get_text()+'\n\r' ))

    url = __BASEURL__ + element.get('href')

    print url

    soup = BeautifulSoup(urllib.urlopen(url))

    lv2ELements = soup.html.body.find('table','tblist').find_all('tr')

    for item in lv2ELements:
        addr = item.find('td','t').find('a').get_text()
        phone = item.find('td','tdl').find('b','tele').get_text()
        f.write('地址:'+addr +' 电话:'+ phone + '\r\n\r')

f.close()

直接执行后,存在 data1.txt中就会有商家的地址和电话等信息。
BeautifulSoup  api 的地址为: http://www.crummy.com/software/BeautifulSoup/bs4/doc/

相关文章

Python网络爬虫实例讲解

Python网络爬虫实例讲解

聊一聊Python与网络爬虫。 1、爬虫的定义 爬虫:自动抓取互联网数据的程序。 2、爬虫的主要框架 爬虫程序的主要框架如上图所示,爬虫调度端通过URL管理器获取待爬取的URL链接,若...

Python中urllib+urllib2+cookielib模块编写爬虫实战

Python中urllib+urllib2+cookielib模块编写爬虫实战

超文本传输协议http构成了万维网的基础,它利用URI(统一资源标识符)来识别Internet上的数据,而指定文档地址的URI被称为URL(既统一资源定位符),常见的URL指向文件、目录...

Python爬虫实例_城市公交网络站点数据的爬取方法

Python爬虫实例_城市公交网络站点数据的爬取方法

爬取的站点:http://beijing.8684.cn/ (1)环境配置,直接上代码: # -*- coding: utf-8 -*- import requests ##导入r...

Python3环境安装Scrapy爬虫框架过程及常见错误

Windows •安装lxml 最好的安装方式是通过wheel文件来安装,http://www.lfd.uci.edu/~gohlke/pythonlibs/,从该网站找到l...

Python HTML解析器BeautifulSoup用法实例详解【爬虫解析器】

本文实例讲述了Python HTML解析器BeautifulSoup用法。分享给大家供大家参考,具体如下: BeautifulSoup简介 我们知道,Python拥有出色的内置HTML解...