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

直接上代码:

代码如下:

#!/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(‘p’,’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/

Posted in 未分类

发表评论