1. 程式人生 > 實用技巧 >Python爬蟲——基於xpath爬取58同城房源資訊!

Python爬蟲——基於xpath爬取58同城房源資訊!

1、需求

獲取58同城上所有房源的標題資訊
https://bj.58.com/ershoufang/

2、分析

使用抓包工具進行分析

發現所有的房源標題資訊,均存在於ul屬性class=house-list-wrap下的li標題中

用xpath形式寫為://ul[@class=“house-list-wrap”]/li


具體的內容存在於li標籤下第二個div標籤的a標籤中。

用xpath形式寫為://ul[@class=“house-list-wrap”]/li/div[2]/h2/a/text()

3、程式碼

from lxml import etree
import requests

if __name__ == "__main__":
    url = 'https://bj.58.com/ershoufang/'
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'
    }
    # 爬取到頁面原始碼資料
    page_text = requests.get(url=url,headers=headers).text
    # 資料解析
    tree = etree.HTML(page_text)
    # 儲存li標籤物件
    li_list = tree.xpath('//ul[@class="house-list-wrap"]/li')
    with open('./58.txt','w',encoding='utf-8') as fp:
        for li in li_list:
            title = li.xpath('./div[2]/h2/a/text()')
            print(title)
            fp.write(title+'\n')

4、實現效果


原始碼或者完整程式碼加群:1136192749