① python 爬蟲代碼 有了爬蟲代碼怎麼運行
打開python爬蟲代碼的源碼目錄,通常開始文件為,init.py,start.py,app.py尋找有沒有類似的python文件,如果沒有,請看源碼的readme文件,裡面會有說明,若以上都沒有,你可能需要python方面的知識,自己去看源碼,找到入口方法並運行
找到入口文件後,在當前目錄打開控制台,輸入python
正常情況下會出現下圖的提示,若沒有,請檢查當前pc的python環境是否有被正確安裝
最後,運行入口文件,輸入python ***.py(入口文件),運行爬蟲
② 誰會用python編寫爬取淘寶商品信息的爬蟲
店鋪及時上新產品,沒有持續更新產品的店鋪是就如同沒有生命力的一潭死水一樣,保持持續的上新,才可以不斷引進流量。
③ 如何用python爬蟲通過搜索獲取某站上的商品圖片
一般用raw_input,input會執行一次求值,一般不是想要的效果。
urlopen,貌似需要自己手動進行url編碼,否則中文參數請求會失敗。
④ python 爬蟲爬取商品信息,不知道代碼哪裡寫錯了,大神求指點。
except Exception as e:
⑤ 如何爬蟲天貓店鋪數據python
本編博客是關於爬取天貓店鋪中指定店鋪的所有商品基礎信息的爬蟲,爬蟲運行只需要輸入相應店鋪的域名名稱即可,信息將以csv表格的形式保存,可以單店爬取也可以增加一個循環進行同時爬取。
源碼展示
首先還是完整代碼展示,後面會分解每個函數的意義。
# -*- coding: utf-8 -*-
import requests
import json
import csv
import random
import re
from datetime import datetime
import time
class TM_procs(object):
def __init__(self,storename):
self.storename = storename
self.url = ''.format(storename)
self.headers = {
"user-agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 "
"(KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"
}
datenum = datetime.now().strftime('%Y%m%d%H%M')
self.filename = '{}_{}.csv'.format(self.storename, datenum)
self.get_file()
def get_file(self):
'''創建一個含有標題的表格'''
title = ['item_id','price','quantity','sold','title','totalSoldQuantity','url','img']
with open(self.filename,'w',newline='') as f:
writer = csv.DictWriter(f,fieldnames=title)
writer.writeheader()
return
def get_totalpage(self):
'''提取總頁碼數'''
num = random.randint(83739921,87739530)
enrl = '/shop/shop_auction_search.do?sort=s&p=1&page_size=12&from=h5&ajson=1&_tm_source=tmallsearch&callback=jsonp_{}'
url = self.url + enrl.format(num)
html = requests.get(url,headers=self.headers).text
infos = re.findall('(({.*}))',html)[0]
infos = json.loads(infos)
totalpage = infos.get('total_page')
return int(totalpage)
def get_procts(self,page):
'''提取單頁商品列表'''
num = random.randint(83739921, 87739530)
enrl = '/shop/shop_auction_search.do?sort=s&p={}&page_size=12&from=h5&ajson=1&_tm_source=tmallsearch&callback=jsonp_{}'
url = self.url + enrl.format(page,num)
html = requests.get(url, headers=self.headers).text
infos = re.findall('(({.*}))', html)[0]
infos = json.loads(infos)
procts = infos.get('items')
title = ['item_id', 'price', 'quantity', 'sold', 'title', 'totalSoldQuantity', 'url', 'img']
with open(self.filename, 'a', newline='') as f:
writer = csv.DictWriter(f, fieldnames=title)
writer.writerows(procts)
def main(self):
'''循環爬取所有頁面寶貝'''
total_page = self.get_totalpage()
for i in range(1,total_page+1):
self.get_procts(i)
print('總計{}頁商品,已經提取第{}頁'.format(total_page,i))
time.sleep(1+random.random())
if __name__ == '__main__':
storename = 'uniqlo'
tm = TM_procs(storename)
tm.main()
上面代碼是選擇了優衣庫作為測試店鋪,直接輸入優衣庫店鋪的域名中關鍵詞即可,最終表格會按照店鋪名稱和時間名詞。
代碼解讀
導入庫說明
requests庫不用多數,爬取網頁的主要庫
json庫是用來解析 json 格式的數據的,也就是 Python 中的字典格式
csv庫是用來創建 csv 表格和保存信息的
random庫是用來生成一個隨機數的,這個代碼中用到了兩次,第一次是生成一個隨機數據去獲取最新的網頁信息而不是緩存信息,第二次是隨機一個時間,來減緩爬蟲速度
re庫是正則,主要用來提取信息
datetime和time都是時間庫,前者一般用來生成當前時間字元串,後者本爬蟲使用設置延遲時間
爬蟲思路
首先通過分析手機端天貓店鋪所有商品的網頁,可以發現每次下滑一頁都有一個 js 被載入,這個 js 的規律可以總結一下;
通過分析可以發現每次請求 js 都可以得到一個關鍵信息,那就是 total_page 這個參數,這也一想就能猜到,就是當前店鋪的總頁碼數,所以可以先取得這個數字,然後使用循環爬取全店商品;
每一頁有24個商品,而請求得到的是一個類似於 json 格式的網頁信息,但是並非是直接的 json,所以可以用正則表達式提取符合 json 格式的部分留用;
將每一頁的信息保存到 csv 表格中,可以直接使用 csv 庫的字典存儲方式,非常方便;
得到了單頁的信息,也得到了總頁碼數,只需要一個循環就可以爬取全店的商品了。
構造爬蟲類
上面代碼依次完成以下操作:
首先整個爬蟲是寫成了一個類,在初始化類的時候需要傳遞一個參數,這個參數就是店鋪的名稱。
然後構造出店鋪的所有商品頁面的前半部分,這部分都是不會變的
接著設置一個請求頭
按照當前時間生成一個以時間為依據的字元串,用來給文件命名,然後賦值給文件名稱,確定保存文件的名稱
最後一句是在類生成的時候就運行這個函數,及生成一個帶有標題的表格,後面會說道這個函數的具體含義
⑥ 有沒有易懂的 Python 多線程爬蟲代碼
Python 在程序並行化方面多少有些聲名狼藉。撇開技術上的問題,例如線程的實現和 GIL1,我覺得錯誤的教學指導才是主要問題。常見的經典 Python 多線程、多進程教程多顯得偏「重」。而且往往隔靴搔癢,沒有深入探討日常工作中最有用的內容。
傳統的例子
簡單搜索下「Python 多線程教程」,不難發現幾乎所有的教程都給出涉及類和隊列的例子:
#Example.py'''
Standard Procer/Consumer Threading Pattern
'''import time
import threading
import Queue
class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
while True:
# queue.get() blocks the current thread until
# an item is retrieved.
msg = self._queue.get()
# Checks if the current message is
# the "Poison Pill"
if isinstance(msg, str) and msg == 'quit': # if so, exists the loop
break
# "Processes" (or in our case, prints) the queue item
print "I'm a thread, and I received %s!!" % msg # Always be friendly!
print 'Bye byes!'def Procer():
# Queue is used to share items between
# the threads.
queue = Queue.Queue() # Create an instance of the worker
worker = Consumer(queue) # start calls the internal run() method to
# kick off the thread
worker.start()
# variable to keep track of when we started
start_time = time.time()
# While under 5 seconds..
while time.time() - start_time < 5:
# "Proce" a piece of work and stick it in
# the queue for the Consumer to process
queue.put('something at %s' % time.time()) # Sleep a bit just to avoid an absurd number of messages
time.sleep(1) # This the "poison pill" method of killing a thread.
queue.put('quit') # wait for the thread to close down
worker.join()if __name__ == '__main__':
Procer()
哈,看起來有些像 Java 不是嗎?
我並不是說使用生產者/消費者模型處理多線程/多進程任務是錯誤的(事實上,這一模型自有其用武之地)。只是,處理日常腳本任務時我們可以使用更有效率的模型。
問題在於…
首先,你需要一個樣板類;
其次,你需要一個隊列來傳遞對象;
而且,你還需要在通道兩端都構建相應的方法來協助其工作(如果需想要進行雙向通信或是保存結果還需要再引入一個隊列)。
worker 越多,問題越多
按照這一思路,你現在需要一個 worker 線程的線程池。下面是一篇 IBM 經典教程中的例子——在進行網頁檢索時通過多線程進行加速。
#Example2.py'''
A more realistic thread pool example
'''import time
import threading
import Queue
import urllib2
class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
while True:
content = self._queue.get()
if isinstance(content, str) and content == 'quit': break
response = urllib2.urlopen(content) print 'Bye byes!'def Procer():
urls = [ 'http', 'httcom'
'ala.org', 'hle.com'
# etc..
]
queue = Queue.Queue()
worker_threads = build_worker_pool(queue, 4)
start_time = time.time() # Add the urls to process
for url in urls:
queue.put(url)
# Add the poison pillv
for worker in worker_threads:
queue.put('quit') for worker in worker_threads:
worker.join() print 'Done! Time taken: {}'.format(time.time() - start_time)def build_worker_pool(queue, size):
workers = [] for _ in range(size):
worker = Consumer(queue)
worker.start()
workers.append(worker) return workersif __name__ == '__main__':
Procer()
這段代碼能正確的運行,但仔細看看我們需要做些什麼:構造不同的方法、追蹤一系列的線程,還有為了解決惱人的死鎖問題,我們需要進行一系列的 join 操作。這還只是開始……
至此我們回顧了經典的多線程教程,多少有些空洞不是嗎?樣板化而且易出錯,這樣事倍功半的風格顯然不那麼適合日常使用,好在我們還有更好的方法。
何不試試 map
map 這一小巧精緻的函數是簡捷實現 Python 程序並行化的關鍵。map 源於 Lisp 這類函數式編程語言。它可以通過一個序列實現兩個函數之間的映射。
urls = ['ho.com', 'htdit.com']
results = map(urllib2.urlopen, urls)
上面的這兩行代碼將 urls 這一序列中的每個元素作為參數傳遞到 urlopen 方法中,並將所有結果保存到 results 這一列表中。其結果大致相當於:
results = []for url in urls:
results.append(urllib2.urlopen(url))
map 函數一手包辦了序列操作、參數傳遞和結果保存等一系列的操作。
為什麼這很重要呢?這是因為藉助正確的庫,map 可以輕松實現並行化操作。
在 Python 中有個兩個庫包含了 map 函數: multiprocessing 和它鮮為人知的子庫 multiprocessing.mmy.
這里多扯兩句: multiprocessing.mmy? mltiprocessing 庫的線程版克隆?這是蝦米?即便在 multiprocessing 庫的官方文檔里關於這一子庫也只有一句相關描述。而這句描述譯成人話基本就是說:"嘛,有這么個東西,你知道就成."相信我,這個庫被嚴重低估了!
mmy 是 multiprocessing 模塊的完整克隆,唯一的不同在於 multiprocessing 作用於進程,而 mmy 模塊作用於線程(因此也包括了 Python 所有常見的多線程限制)。
所以替換使用這兩個庫異常容易。你可以針對 IO 密集型任務和 CPU 密集型任務來選擇不同的庫。2
動手嘗試
使用下面的兩行代碼來引用包含並行化 map 函數的庫:
from multiprocessing import Poolfrom multiprocessing.mmy import Pool as ThreadPool
實例化 Pool 對象:
pool = ThreadPool()
這條簡單的語句替代了 example2.py 中 build_worker_pool 函數 7 行代碼的工作。它生成了一系列的 worker 線程並完成初始化工作、將它們儲存在變數中以方便訪問。
Pool 對象有一些參數,這里我所需要關注的只是它的第一個參數:processes. 這一參數用於設定線程池中的線程數。其默認值為當前機器 CPU 的核數。
一般來說,執行 CPU 密集型任務時,調用越多的核速度就越快。但是當處理網路密集型任務時,事情有有些難以預計了,通過實驗來確定線程池的大小才是明智的。
pool = ThreadPool(4) # Sets the pool size to 4
線程數過多時,切換線程所消耗的時間甚至會超過實際工作時間。對於不同的工作,通過嘗試來找到線程池大小的最優值是個不錯的主意。
創建好 Pool 對象後,並行化的程序便呼之欲出了。我們來看看改寫後的 example2.py
import urllib2
from multiprocessing.mmy import Pool as ThreadPool
urls = [ 'httorg',
'hon.org/about/',
'hnlamp.com/pub/a/python/2003/04/17/metaclasses.html',
# etc..
]
# Make the Pool of workers
pool = ThreadPool(4)
# Open the urls in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)
#close the pool and wait for the work to finish
pool.close()
pool.join()
實際起作用的代碼只有 4 行,其中只有一行是關鍵的。map 函數輕而易舉的取代了前文中超過 40 行的例子。為了更有趣一些,我統計了不同方法、不同線程池大小的耗時情況。
# results = [] # for url in urls:# result = urllib2.urlopen(url)# results.append(result)# # ------- VERSUS ------- # # # ------- 4 Pool ------- # # pool = ThreadPool(4) # results = pool.map(urllib2.urlopen, urls)# # ------- 8 Pool ------- # # pool = ThreadPool(8) # results = pool.map(urllib2.urlopen, urls)# # ------- 13 Pool ------- # # pool = ThreadPool(13) # results = pool.map(urllib2.urlopen, urls)
結果:
# Single thread: 14.4 Seconds # 4 Pool: 3.1 Seconds# 8 Pool: 1.4 Seconds# 13 Pool: 1.3 Seconds
很棒的結果不是嗎?這一結果也說明了為什麼要通過實驗來確定線程池的大小。在我的機器上當線程池大小大於 9 帶來的收益就十分有限了。
⑦ 如何用python寫一個爬蟲統計淘寶某件商品的銷量
s1.listen( backlog )
#backlog指定最多允許多少個客戶連接到伺服器。它的值至少為1。收到連接請求後,這些請求需要排隊,如果隊列滿,就拒絕請求。
⑧ 如何利用python寫爬蟲程序
利用python寫爬蟲程序的方法:
1、先分析網站內容,紅色部分即是網站文章內容div。
⑨ 如何用python實現淘寶搜索商品並點擊進入商品頁面
這個和用不用python沒啥關系,是數據來源的問題。 調用淘寶API,使用 api相關介面獲得你想要的內容,我 記得api中有相關的介面,你可以看一下介面的說明。 用python做爬蟲來進行頁面數據的獲齲 希望能幫到你。
⑩ 請教Python爬蟲:如果想用Python爬下面網頁的價格,請問應該怎樣做
用爬蟲跟蹤下一頁的方法是自己模擬點擊下一頁連接,然後發出新的請求;
參考例子如下:
item1 = Item()
yield item1
item2 = Item()
yield item2
req = Request(url='下一頁的鏈接', callback=self.parse)
yield req
注意:使用yield時不要用return語句。