【发布时间】:2018-11-21 16:43:13
【问题描述】:
我用 Python 结合 BeautifulSoup 编写了一个脚本来提取书名,这些书名是在亚马逊搜索框中提供一些 ISBN 号后填充的。我从名为amazon.xlsx 的excel 文件中提供这些ISBN 编号。当我尝试使用以下脚本时,它会相应地解析标题并按预期写回 excel 文件。
The link where I put isbn numbers to populate the results.
import requests
from bs4 import BeautifulSoup
from openpyxl import load_workbook
wb = load_workbook('amazon.xlsx')
ws = wb['content']
def get_info(num):
params = {
'url': 'search-alias=aps',
'field-keywords': num
}
res = requests.get("https://www.amazon.com/s/ref=nb_sb_noss?",params=params)
soup = BeautifulSoup(res.text,"lxml")
itemlink = soup.select_one("a.s-access-detail-page")
if itemlink:
get_data(itemlink['href'])
def get_data(link):
res = requests.get(link)
soup = BeautifulSoup(res.text,"lxml")
try:
itmtitle = soup.select_one("#productTitle").get_text(strip=True)
except AttributeError: itmtitle = "N\A"
print(itmtitle)
ws.cell(row=row, column=2).value = itmtitle
wb.save("amazon.xlsx")
if __name__ == '__main__':
for row in range(2, ws.max_row + 1):
if ws.cell(row=row,column=1).value==None:break
val = ws["A" + str(row)].value
get_info(val)
但是,当我尝试使用 multiprocessing 执行相同操作时,我收到以下错误:
ws.cell(row=row, column=2).value = itmtitle
NameError: name 'row' is not defined
对于multiprocessing,我在脚本中带来的更改是:
from multiprocessing import Pool
if __name__ == '__main__':
isbnlist = []
for row in range(2, ws.max_row + 1):
if ws.cell(row=row,column=1).value==None:break
val = ws["A" + str(row)].value
isbnlist.append(val)
with Pool(10) as p:
p.map(get_info,isbnlist)
p.terminate()
p.join()
我尝试过的几个 ISBN:
9781584806844
9780917360664
9780134715308
9781285858265
9780986615108
9780393646399
9780134612966
9781285857589
9781453385982
9780134683461
如何使用multiprocessing 消除该错误并获得所需的结果?
【问题讨论】:
标签: python python-3.x web-scraping multiprocessing openpyxl