1. 程式人生 > >使用requests配合【lxml+xpath】爬取B2B網站

使用requests配合【lxml+xpath】爬取B2B網站

@匯入類庫

import requests
from lxml import etree
import time

@準備請求頭,以偽裝客戶端瀏覽器

# 請求頭,可以由F12頁面控制檯或fidder等抓包工具獲取
header_base = {
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
    'Upgrade-Insecure-Requests'
: '1', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', }

@逐頁爬取資料,並寫入檔案

    # 要爬取資料的 url
    url_str = 'http://sell.gandianli.com/list.php?catid=3234&page=1'

    # 傳送請求,接受響應
res = requests.get(url=url_str, headers=header_base) # print(res.text) # print(res.status_code) # 獲得元素樹 html = etree.HTML(res.text) # 獲取所有class屬性為pages的div元素下的cite元素的文字 # 此處是為了獲得分頁資料的總頁面數 elements = html.xpath("//div[@class='pages']/cite/text()") # 提取出頁面數 page_count = int(elements[0
].split('/')[1][:-1]) # 開啟檔案,爬取並寫入內容 with open("products.csv","a",encoding="utf-8") as file: # 逐個爬取每一頁內容 for i in range(1, page_count + 1): # 爬取頁面內容 get_one_page(i,file) # 休息一下再爬取,訪問頻率過高容易被封IP time.sleep(3)

@get_one_page函式實現,其功能是爬取單頁內容

# 爬取單頁內容
# page_num = 頁碼
# file = 要寫入的檔案
def get_one_page(page_num,file):
    # 構造具體頁面的url(使用抓包工具或頁面控制檯分析獲取)
    url_str = 'http://sell.gandianli.com/list.php?catid=3234&page=' + str(page_num)
    print(url_str)

    # 傳送請求,接受響應
    res = requests.get(url=url_str, headers=header_base)
    # print(res.status_code)
    # print(res.text)

    # 得到頁面元素樹物件
    html = etree.HTML(res.text)

    # 使用 XPATH 規則提取裡面的資訊

    '''
    # txt_list = html.xpath("//ul[@class='extension_ul']/li/h3/a/text()")
    for txt in txt_list:
        print(txt)
    '''

    # 提取所有class屬性為extension_ul的無序列表下的li元素
    li_list = html.xpath("//ul[@class='extension_ul']/li")

    # 迴圈訪問 每個 li
    for li in li_list:

        # 從li元素中提取產品名稱、價格、公司資訊
        texts = li.xpath("./h3/a/text() \
                  | ./div[@class='extension_right']/span/text()  \
                  | ./div[@class='extension_right']/p[1]/a/text()")
        # print(texts)
        # print(len(texts))

        # 定義一個結果列表,用於儲存處理後的資料
        result_list = []

        # 遍歷和清洗資料
        for txt in texts:

            # 判斷去除空格後的資料是否為空,若為空,則丟棄
            tmp = txt.strip()
            if tmp:
                result_list.append(txt.strip())

        # 判斷資料數量是否正確,否則丟棄
        if len(result_list) == 3:

            # 將產品名稱、價格、公司使用逗號分割,組織在一起
            # 這裡推薦使用英文逗號,因為便於轉化為csv檔案,以供將來做資料分析
            item = ','.join(result_list)
            print(item)

            # 將資料拼接,並寫入檔案
            file.write(item + '\n')

@實現效果
描述你妹啊