导航:首页 > 编程语言 > 购买商品python爬虫代码

购买商品python爬虫代码

发布时间:2022-08-31 19:13:27

python 爬虫代码 有了爬虫代码怎么运行

② 谁会用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()

上面代码是选择了优衣库作为测试店铺,直接输入优衣库店铺的域名中关键词即可,最终表格会按照店铺名称和时间名词。

代码解读

导入库说明

⑥ 有没有易懂的 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语句。

阅读全文

与购买商品python爬虫代码相关的资料

热点内容
广东编程猫学习班 浏览:704
上海数控编程培训学校 浏览:311
怎么下载我的解压神器 浏览:632
lib文件无用代码会编译吗 浏览:26
我的世界嗨皮咳嗽服务器怎么下 浏览:1000
mvn命令顺序 浏览:978
车贷还完多少时间解压 浏览:964
java页面开发 浏览:816
学编程的小发明 浏览:25
为什么说程序员喜欢格子 浏览:253
代码编译后叫什么 浏览:969
电脑文件夹做了保护怎么删除 浏览:678
php数据库连接全局 浏览:528
葫芦岛有程序员吗 浏览:986
小胖机器人显示无命令 浏览:775
一日一画pdf 浏览:99
编程猫拔萝卜文字评价模板 浏览:254
cmdjava命令 浏览:239
扫描版pdf转文字版 浏览:536
单片机专用寄存器 浏览:502