多进程爬取星巴克
本帖最后由 ∫護着妳佉遠方 于 2022-1-31 15:40 编辑使用进程池爬取星巴克的完整代码
"""
* @codding : utf-8
* @time: 2022/1/29 13:27:28
* @name : 09_多线程爬取.py
* @system: Windows 11
* @Types : pythonProject
* @software : PyCharm
* @author :
"""
import re
import time
import urllib.parse
import urllib.request
from multiprocessing import Pool
import requests
from bs4 import BeautifulSoup
def producer():
url = 'https://www.starbucks.com.cn/menu/'
head = {
'Cookie': 'ZHh6ku4z=AMCsJHZ-AQAAOcyxX6Yl2s20HjtkZfHK87MTPofIn6iYXJHzUvqd_HT1ZDMD|1|0'
'|36c0e1a8addcb91415dc5a8a4223425eca69e3d4',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
'like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.76'
}
# 请求对象定制
request = urllib.request.Request(url=url, headers=head)
#模拟浏览器向服务器发送请求
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
# print(content)
soup = BeautifulSoup(content, 'lxml')
# 名称
# //ul[@class="grid padded-3 product"]//strong/text()
# 名称列表
name_list = soup.select('ul strong')
# 图片列表.jpg
# //ul[@class="grid padded-3 product"]//div/@style
img_lisi = soup.select('ul div')
tinydict = {}
for i in range(len(name_list)):
name = name_list
aaa = name.get_text()
yyy = re.sub('/', ',', aaa)
img = img_lisi
bbb = img.attrs.get('style')
ccc = re.findall(r'url\("(.*)"\)', bbb)
ddd = 'https://www.starbucks.com.cn' + ccc
xx = {yyy: ddd}
tinydict.update(xx)
# print(list)
return tinydict
def consumer(tinydict):
name = tinydict
img = tinydict
# print(name, img)
f = open(name + '.jpg', 'wb')
d = requests.get(img).content
f.write(d)
f.close()
print('成功下载', name)
if __name__ == '__main__':
tinydict = producer()
# print(list)
pool = Pool(processes=4)
pool.map(consumer, tinydict.items())
第74行能正常打印,但是65行打印就有问题,求助解决办法 本帖最后由 水墨青云 于 2022-1-31 13:37 编辑
https://www.runoob.com/python/python-func-map.html
我也初学,别用关键字作为变量名啊
list 是列表,为啥给它字典的格式def producer():
a = {'1':2,'2':3,'3':4}
return a
def consumer(a):
print(a)
if __name__ == '__main__':
a = producer()
print(a)
list(map(consumer, a))
输出:
{'1': 2, '2': 3, '3': 4}
1
2
3
水墨青云 发表于 2022-1-31 13:33
https://www.runoob.com/python/python-func-map.html
我也初学,别用关键字作为变量名啊
list 是列表, ...
好吧,我忘记关键词这种事情了,我在试试 水墨青云 发表于 2022-1-31 13:33
https://www.runoob.com/python/python-func-map.html
我也初学,别用关键字作为变量名啊
list 是列表, ...
试了,不是名字的原因, 你这个pool是多进程吧?
对多线程和多进程是不是混淆了? thepoy 发表于 2022-1-31 15:12
你这个pool是多进程吧?
对多线程和多进程是不是混淆了?
是的,确实是进程,不过问题解决了,多谢提醒 大神666666666 小恒 发表于 2022-1-31 18:50
大神666666666
别大神了遇到问题了,太难受了
有兴趣研究一下
https://www.52pojie.cn/thread-1581805-1-1.html 学习学习
页:
[1]
2