1. 程式人生 > >爬蟲練習 -- 鏈家

爬蟲練習 -- 鏈家

注意:請不要爬取過多資訊,僅供學習。

分析:

  1. 業務需求分析......(此例為住房資訊...)
  2. 查詢相關網頁資訊(以鏈家為例)
  3. 分析URL,查詢我們需要的內容,建立連線
  4. 定位資料
  5. 儲存資料

首先進入鏈家網首頁,點選租房,F12檢查網頁,查詢我們需要的資訊。如圖:

然後再定位我們需要的資訊:如下圖

下面就開始程式碼實現,我們的分析過程,獲取資料,對資料進行定位。

主要程式碼:

  1. # url 頁碼拼接

  2. url = 'https://bj.lianjia.com/zufang/pg{}'.format(page)

  1. # 利用Xpath 對資料進行定位

  2. ...

  3. html_pipei = html_ele.xpath('//ul[@id="house-lst"]/li')

  4. for pipei_one in html_pipei:

  5. title = pipei_one.xpath('./div[2]/h2/a')[0].text

  6. region = pipei_one.xpath('./div[2]/div[1]/div[1]/a/span')[0].text

  7. ...

完整程式碼如下:

  1. import requests

  2. from lxml import etree

  3. import pymysql

  4. class Mysql(object):

  5. '''執行資料操作封裝類'''

  6. def __init__(self):

  7. '''連線資料庫、建立遊標'''

  8. self.db = pymysql.connect(host="localhost", user="root", password="8888", database="test")

  9. self.cursor = self.db.cursor()

  10. def mysql_op(self, sql, data):

  11. '''MySQL語句'''

  12. self.cursor.execute(sql, data)

  13. self.db.commit()

  14. def __del__(self):

  15. '''關閉遊標、關閉資料庫'''

  16. self.cursor.close()

  17. self.db.close()

  18. # MySQL語句

  19. Insert = Mysql()

  20. # 要執行的sql 語句

  21. sql = '''INSERT INTO lianjia (title, region, zone, meters, location, price) VALUES(%s, %s, %s, %s, %s, %s)'''

  22. # 頭部報文

  23. headers = {

  24. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'

  25. }

  26. def download_msg():

  27. for page in range(1, 2):

  28. url = 'https://bj.lianjia.com/zufang/pg{}'.format(page)

  29. responses = requests.get(url, headers=headers)

  30. html = responses.text

  31. # 利用Xpath

  32. html_ele = etree.HTML(html)

  33. html_pipei = html_ele.xpath('//ul[@id="house-lst"]/li')

  34. # print(html_pipei)

  35. for pipei_one in html_pipei:

  36. # ./li/div[2]/a

  37. title = pipei_one.xpath('./div[2]/h2/a')[0].text

  38. # print(title)

  39. region = pipei_one.xpath('./div[2]/div[1]/div[1]/a/span')[0].text

  40. # print(region)

  41. zone = pipei_one.xpath('./div[2]/div[1]/div[1]/span[1]/span')[0].text

  42. # print(zone)

  43. meters = pipei_one.xpath('./div[2]/div[1]/div[1]/span[2]')[0].text

  44. # print(meters)

  45. location = pipei_one.xpath('./div[2]/div[1]/div[1]/span[3]')[0].text

  46. # print(location)

  47. price = pipei_one.xpath('.//div[@class="price"]/span')[0].text

  48. # print(price)

  49. data = (title, region, zone, meters, location, price)

  50. Insert.mysql_op(sql, data)

  51. if __name__ == '__main__':

  52. download_msg()