目錄
前言
一、介紹
二、爬蟲流程
1. 確定關(guān)鍵詞并構(gòu)造URL
2. 發(fā)送網(wǎng)絡(luò)請求
3. 解析HTML并提取數(shù)據(jù)
4. 保存數(shù)據(jù)
三、使用代理IP
四、完整代碼
五、總結(jié)
前言
閑魚是一個很受歡迎的二手交易平臺,但是由于沒有開放API,我們需要使用爬蟲來獲取數(shù)據(jù)。本文將介紹如何使用Python爬蟲爬取閑魚上的商品信息,包括構(gòu)造URL、發(fā)送網(wǎng)絡(luò)請求、解析HTML并提取數(shù)據(jù)以及使用代理IP來進行爬取。如果您需要抓取閑魚的其他數(shù)據(jù),本文也提供了一些參考。
一、介紹
隨著電子商務(wù)的興起,二手交易平臺也變得越來越受歡迎。作為淘寶旗下的二手交易平臺,閑魚的日活躍用戶已經(jīng)超過了1億。因此,對于一些商家和買家來說,閑魚是一個極具吸引力的平臺。
對于我們開發(fā)者來說,有時候我們需要從閑魚上抓取一些數(shù)據(jù),比如價格走勢,熱門商品,關(guān)鍵詞排名等等。但是,閑魚并沒有開放API,這就需要我們使用爬蟲來獲取數(shù)據(jù)。
本文將詳細介紹如何使用Python爬蟲爬取閑魚上的商品信息。我們將主要使用requests庫和BeautifulSoup庫來完成這個任務(wù)。此外,為了避免被閑魚封禁IP地址,我們還將使用代理IP來進行爬取。
二、爬蟲流程
要完成我們的閑魚爬蟲,我們需要掌握以下幾個步驟:
1. 確定關(guān)鍵詞并構(gòu)造URL
在爬取閑魚數(shù)據(jù)之前,首先我們需要確定要搜索的關(guān)鍵詞。這個關(guān)鍵詞可以是任何你想要的內(nèi)容,比如“二手手機”、“二手電腦”等等。
根據(jù)我們選擇的關(guān)鍵詞,我們需要構(gòu)造一個URL,即閑魚商品搜索的URL。URL的構(gòu)造方法如下:
url = "https://2.taobao.com/search/index.htm?q={}&search_type=item&app=shopsearch".format(keyword)
其中,keyword為我們選擇的關(guān)鍵詞。
2. 發(fā)送網(wǎng)絡(luò)請求
我們使用requests庫來發(fā)送網(wǎng)絡(luò)請求:
headers = {
? ?'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36'}
response = requests.get(url, headers=headers)
在發(fā)送請求之前,我們需要設(shè)置請求頭。這個請求頭包含了我們?yōu)g覽器的信息,這樣可以避免被服務(wù)器輕易識別為爬蟲。
3. 解析HTML并提取數(shù)據(jù)
我們使用BeautifulSoup庫來解析HTML并提取數(shù)據(jù):
soup = BeautifulSoup(response.text, 'html.parser')
goods_list = soup.find_all('div', {'class': 'J_MouserOnverReq'})
解析完HTML之后,我們需要找出包含商品信息的標(biāo)簽。我們可以通過查看閑魚網(wǎng)頁的源代碼,找到所有商品信息都被包含在一個class為“J_MouserOnverReq”的div中。
4. 保存數(shù)據(jù)
最后一步,我們需要將爬取到的數(shù)據(jù)保存下來。這里我們使用csv庫將數(shù)據(jù)保存到csv文件中。
with open('goods_info.csv', 'w', newline='') as f:
? ? writer = csv.writer(f)
? ? writer.writerow(['商品名稱', '商品價格', '商品鏈接'])
? ? for goods in goods_list:
? ? ? ? title = goods.find('p', {'class': 'item-title'}).text.strip()
? ? ? ? price = goods.find('p', {'class': 'price'}).text.strip()
? ? ? ? link = goods.find('a', {'class': 'item-link'}).get('href')
? ? ? ? writer.writerow([title, price, link])
通過使用以上四個步驟,我們可以完成閑魚商品信息的爬蟲。
三、使用代理IP
由于頻繁的發(fā)送網(wǎng)絡(luò)請求會使服務(wù)器懷疑我們是爬蟲,并且封禁我們的IP地址,所以我們需要使用代理IP來隱藏我們的真實IP地址。
我們可以從代理IP網(wǎng)站上獲取代理IP。這里我們使用站大爺?shù)腁PI,可以通過以下的代碼來獲取代理IP:
def get_proxies():
? ? response = requests.get("http://ip.zdaye.com/dayProxy.html")
? ? soup = BeautifulSoup(response.text, 'html.parser')
? ? trs = soup.find_all('tr')
? ? proxies = []
? ? for tr in trs[1:]:
? ? ? ? tds = tr.find_all('td')
? ? ? ? ip = tds[0].text.strip()
? ? ? ? port = tds[1].text.strip()
? ? ? ? protocol = tds[3].text.strip().lower()
? ? ? ? proxies.append("{}://{}:{}".format(protocol, ip, port))
? ? return proxies
該函數(shù)會返回一個代理IP池。
我們可以在發(fā)送網(wǎng)絡(luò)請求的時候使用代理IP,代碼如下:
proxies = {
? ? "http": random.choice(get_proxies()),
? ? "https": random.choice(get_proxies())
}
response = requests.get(url, headers=headers, proxies=proxies)
在構(gòu)造requests對象的時候,我們傳入proxies參數(shù),代表我們使用一個代理IP來發(fā)送網(wǎng)絡(luò)請求。文章來源:http://www.zghlxwxcb.cn/news/detail-721215.html
四、完整代碼
import csv
import random
import requests
from bs4 import BeautifulSoup
def get_proxies():
? ? """
? ? 獲取代理IP
? ? """
? ? response = requests.get("http://ip.zdaye.com/dayProxy.html")
? ? soup = BeautifulSoup(response.text, 'html.parser')
? ? trs = soup.find_all('tr')
? ? proxies = []
? ? for tr in trs[1:]:
? ? ? ? tds = tr.find_all('td')
? ? ? ? ip = tds[0].text.strip()
? ? ? ? port = tds[1].text.strip()
? ? ? ? protocol = tds[3].text.strip().lower()
? ? ? ? proxies.append("{}://{}:{}".format(protocol, ip, port))
? ? return proxies
def get_goods_info(keyword):
? ? """
? ? 爬取商品信息
? ? """
? ? url = "https://2.taobao.com/search/index.htm?q={}&search_type=item&app=shopsearch".format(keyword)
? ? headers = {
? ? ? ? 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
? ? ? ? ? ? ? ? ? ? ? 'Chrome/58.0.3029.96 Safari/537.36'}
? ? proxies = {
? ? ? ? "http": random.choice(get_proxies()),
? ? ? ? "https": random.choice(get_proxies())
? ? }
? ? response = requests.get(url, headers=headers, proxies=proxies)
? ? soup = BeautifulSoup(response.text, 'html.parser')
? ? goods_list = soup.find_all('div', {'class': 'J_MouserOnverReq'})
? ? with open('goods_info.csv', 'w', newline='') as f:
? ? ? ? writer = csv.writer(f)
? ? ? ? writer.writerow(['商品名稱', '商品價格', '商品鏈接'])
? ? ? ? for goods in goods_list:
? ? ? ? ? ? title = goods.find('p', {'class': 'item-title'}).text.strip()
? ? ? ? ? ? price = goods.find('p', {'class': 'price'}).text.strip()
? ? ? ? ? ? link = goods.find('a', {'class': 'item-link'}).get('href')
? ? ? ? ? ? writer.writerow([title, price, link])
if __name__ == '__main__':
? ? get_goods_info('二手手機')
五、總結(jié)
本文介紹了如何使用Python爬蟲爬取閑魚上的商品信息,并且使用代理IP防止被封禁IP地址。如果您還需要爬取其他數(shù)據(jù),比如評論、店鋪信息等等,您可以根據(jù)本文提到的方法進行嘗試。文章來源地址http://www.zghlxwxcb.cn/news/detail-721215.html
到了這里,關(guān)于【python爬蟲】閑魚爬蟲,可以爬取商品的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!