【发布时间】:2017-11-25 17:52:54
【问题描述】:
我提取了四个项目(一个字符串列表和三个字符串),我想将所有四个项目写在一行中。我认为这是可能的,只需要一点帮助。
r_ingredients_wtht_tags = []
for link in r_links:
r = requests.get(link)
# print(r.status_code)
if r.status_code == requests.codes.ok:
soup = BeautifulSoup(r.content, "html.parser")
r_name = soup.find('h1', {'itemprop': 'name'}).text.replace('recipe', '')
r_prep_time = soup.select('li.recipe-meta-tag')[1].text
r_ingrdnts_with_tags = soup.select('span[itemprop="ingredients"]')
for r_ingrdnts in r_ingrdnts_with_tags: # Remove span tags from list items
r_ingredients_wtht_tags.append(r_ingrdnts.text)
# print(r_ingredients_wtht_tags)
# exit()
r_image_src = soup.find('img', {'itemprop': 'image'}).get('src')
r_image_url = 'https://website.com' + r_image_src # dummy website
r_url = link
# Download the recipe image
print('Downloading image %s...' % (r_image_url))
rec_image = requests.get(r_image_url)
rec_image.raise_for_status() # Will raise an exception if above request failed.
# Create image folder to store current recipe image
os.makedirs('recipe' + str(image_fold_count), exist_ok=True)
# Save recipe image
imageFile = open(os.path.join('recipe' + str(image_fold_count), os.path.basename(r_image_url)), 'wb')
for chunk in rec_image.iter_content(100000):
imageFile.write(chunk)
imageFile.close()
# write to csv file. NOTE TO SELF: MOVE THIS TO ITS OWN FUNCTION
fileWriter.writerow(zip(r_name, r_prep_time, r_ingredients_wtht_tags, r_url +"\n"))
image_fold_count += 1 # Increment recipe folder counter
【问题讨论】:
-
“为什么这段代码不工作”的密切原因在这里完美适用,所以我将在问题结束之前引用它:“寻求调试帮助的问题(“为什么不是这个代码工作?") 必须包含所需的行为、特定问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:How to create a Minimal, Complete, and Verifiable example。"
-
使用按钮
{}正确格式化代码。 -
为什么用
zip()写csv?你应该使用列表[r_name, r_prep_time, r_ingredients_wtht_tags, r_url +"\n"] -
为什么要把
"\n"加到r_url上?csv将在行尾自动添加\n。 -
如果
r_ingredients_wtht_tags是一个列表,并且您想要分隔单元格中的所有元素然后以这种方式创建列表[r_name, r_prep_time] + r_ingredients_wtht_tags + [r_url]
标签: python python-3.x csv beautifulsoup