1. 程式人生 > >Python爬取安居客經紀人資訊

Python爬取安居客經紀人資訊

Python爬取安居客經紀人資訊

Python2.7.15
今天我們來爬取安居客經紀人的資訊。這次我們不再使用正則,我們使用beautifulsoup。不瞭解的可以先看一下這個文件,便於理解。https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

一、獲取原始碼

for page in range(1,8):
    url ="https://beijing.anjuke.com/tycoon/p" + str(page)+"/"
    response = urllib2.urlopen(url)
    content = response.read()

老套路urllib2

二、使用bs4

首先看原始碼,找到經紀人資訊對應的標籤,然後使用beautifulsoup方法,這裡的html.parser是對應的解析器

    soup = BeautifulSoup(content,'html.parser')
    a = soup.find_all('h3')
    b = soup.find_all(class_=re.compile("brokercard-sd-cont clearfix"))
    c = soup.find_all("p", attrs={"class": "jjr-desc"})
    d = soup.find_all("p", attrs={"class": "jjr-desc xq_tag"})
    e = soup.find_all(class_=re.compile("broker-tags clearfix"))

a,b,c,d,e分別對應經紀人姓名,評價,門店,熟悉,業務
每一項都是列表
將它們迴圈輸出

    n = 0
    for jjr in a:
        o = jjr.get_text(strip=True).encode('utf-8')
        p = b[n].get_text(strip=True).encode('utf-8')
        q = c[2*n].get_text(strip=True).encode('utf-8')
        r = d[n].get_text(strip=True).encode('utf-8')
        s = e[n].get_text(strip=True).encode('utf-8')
        n+=1

這裡要注意編碼問題,使用beautifulsoup解析後的文件是Unicode編碼,直接輸出會亂碼,而且這個編碼模式也無法寫入文件或資料庫,所以後面要加上encode(‘utf-8’)來重新編碼

三、寫入資料庫

        insert_agent = ("INSERT INTO AGENT(姓名,評價,門店,熟悉,業務)" "VALUES(%s,%s,%s,%s,%s)")
        data_agent = (o,p,q,r,s)
        cursor.execute(insert_agent, data_agent)

記得先建立資料庫連線,和要寫入的表

四、完整程式碼

# coding=utf-8
from bs4 import BeautifulSoup
import urllib2
import re
import MySQLdb

conn=MySQLdb.connect(host="127.0.0.1",user="root",passwd="199855pz",db="pz",charset='utf8')
print '連線成功'
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS AGENT")
sql = '''CREATE TABLE AGENT(姓名 char(4) ,評價 char(50) ,門店 char(50) ,熟悉 char(50) ,業務 char(50))'''
cursor.execute(sql)

for page in range(1,8):
    url ="https://beijing.anjuke.com/tycoon/p" + str(page)+"/"
    response = urllib2.urlopen(url)
    content = response.read()
    soup = BeautifulSoup(content,'html.parser')
    a = soup.find_all('h3')
    b = soup.find_all(class_=re.compile("brokercard-sd-cont clearfix"))
    c = soup.find_all("p", attrs={"class": "jjr-desc"})
    d = soup.find_all("p", attrs={"class": "jjr-desc xq_tag"})
    e = soup.find_all(class_=re.compile("broker-tags clearfix"))

    n = 0
    for jjr in a:
        o = jjr.get_text(strip=True).encode('utf-8')
        p = b[n].get_text(strip=True).encode('utf-8')
        q = c[2*n].get_text(strip=True).encode('utf-8')
        r = d[n].get_text(strip=True).encode('utf-8')
        s = e[n].get_text(strip=True).encode('utf-8')
        n+=1
        insert_agent = ("INSERT INTO AGENT(姓名,評價,門店,熟悉,業務)" "VALUES(%s,%s,%s,%s,%s)")
        data_agent = (o,p,q,r,s)
        cursor.execute(insert_agent, data_agent)
conn.commit()

PS.安居客更新了,原始碼有一些變動,但爬取資訊還是老方法。