【发布时间】:2020-08-15 05:14:29
【问题描述】:
在这部分抓取代码中,我从(url.xml)文件中存储的URL中获取了很多URL,并且需要很长时间才能完成,如何实现(多处理池)
有什么简单的代码可以解决这个问题吗?谢谢
from bs4 import BeautifulSoup as soup
import requests
from multiprocessing import Pool
p = Pool(10) # “10” means that 10 URLs will be processed at the same time
p.map
page_url = "url.xml"
out_filename = "prices.csv"
headers = "availableOffers,otherpricess,currentprice \n"
with open(out_filename, "w") as fw:
fw.write(headers)
with open("url.xml", "r") as fr:
for url in map(lambda x: x.strip(), fr.readlines()):
print(url)
response = requests.get(url)
page_soup = soup(response.text, "html.parser")
availableOffers = page_soup.find("input", {"id": "availableOffers"})
otherpricess = page_soup.find("span", {"class": "price"})
currentprice = page_soup.find("div", {"class": "is"})
fw.write(availableOffers + ", " + otherpricess + ", " + currentprice + "\n")
p.terminate()
p.join()
【问题讨论】:
-
我加了
p.terminate() p.join()但还是不行 -
您的地图调用在这里粘贴错误,您需要一个 if name__==' __main'
-
其余代码添加到问题中,不知道应该添加什么,请帮助
-
p.map 不正确。 p.map 需要一个函数和可迭代的参数。您需要将您的请求获取逻辑放在一个以 url 作为参数的函数中。您还需要添加对受 if name == 'main' 保护的 pool(10) 的调用,以便子进程不会创建自己的池。
标签: python import multiprocessing pool