【发布时间】:2021-11-23 11:18:35
【问题描述】:
我试图弄清楚如何正确地将多个值附加到列表中。我正在抓取的网页是一个美食博客。我想检索食谱的标题以及与该特定食谱相关的所有食谱键(无麸质、素食、无乳制品、素食等)。我可以从页面中检索信息,但我遇到的问题是将几个食谱键附加到列表上的单行,所以如果页面上的第一个食谱既不含乳制品又不含麸质,我不是能够附加它们,以便它们与相应配方的行匹配。我正在分享我的一段代码,这样你就可以看到我正在使用什么。提前感谢您的帮助。
recipe = []
key = []
for page in pages:
page = requests.get('https://www.skinnytaste.com/page/'+str(page)+'/')
soup = BeautifulSoup(page.text, 'html.parser')
recipes = soup.find_all('article', class_='post teaser-post odd')
recipes.extend(soup.find_all('article', class_='post teaser-post even'))
sleep(randint(2, 8))
for r in recipes:
titles = r.h2.text
recipe.append(titles)
print(titles)
post_meta = r.find('div', class_='post-meta')
icons = post_meta.find('div', class_='icons')
if not (post_meta.find('div', class_='icons') is None):
keys = icons.find_all('span')
for k in keys:
recipe_key = k.find('a').find('img').get('alt')
key.append(recipe_key)
print(recipe_key)
【问题讨论】:
标签: web-scraping beautifulsoup