我需要项目标题的字符串.该网站是结构化的,每个项目都有这条线.
我的代码看起来像:
#Loading Libraries
import urllib
import urllib.request
from bs4 import BeautifulSoup
#define URL for scraping
theurl = "https://www.kickstarter.com/discover/advanced?category_id=16&woe_id=23424829&sort=popularity&seed=2448324&page=1"
thepage = urllib.request.urlopen(theurl)
#Cooking the Soup
soup = BeautifulSoup(thepage,"html.parser")
#Scraping "Project Title" (project-title)
project_title = soup.find('h6', {'class': 'project-title'}).findChildren('a')
title = project_title[0].text
print (title)
如果我使用soup.find_all或在Project_title [0]行而不是零处设置另一个值,则Python会显示错误.
我需要一份包含本网站所有项目名称的清单.例如.:
>超级本:以99美元的价格将智能手机变成笔记本电脑
>重量:更加智能
>我的Kafon无人机是世界上第一个也是唯一完成的
>天气摄像系统Omega2:带有Wi-Fi的5美元物联网计算机,由
Linux的
解决方法:
find()只返回一个元素.要获得所有,您必须使用findAll
这是您需要的代码
project_elements = soup.findAll('h6', {'class': 'project-title'})
project_titles = [project.findChildren('a')[0].text for project in project_elements]
print(project_titles)
我们查看标签h6和类项目标题的所有元素.然后,我们从每个元素中获取标题,并使用它创建一个列表.
希望它有所帮助,并且毫不犹豫地询问您是否有任何疑问.
编辑:上面代码的问题是,如果我们没有为findAll返回的列表中的每个元素至少获得标记a的子节点,它将失败
如何防止这种情况:
project_titles = [project.findChildren('a')[0].text for project in project_elements if project.findChildren('a')]
只有当project.findChildren(‘a’)作为至少一个元素时,才会创建列表. (如果[]返回False)
编辑:要获得元素的描述(类project-blurb),让我们看一下HTML代码.
Bagel is a digital tape measure that helps you measure, organize, and analyze any size measurements in a smart way.
这只是class-blurb的一个段落.为了得到它们,我们可以使用与获取project_elements相同的方法,或者更精简:
project_desc = [description.text for description in soup.findAll('p', {'class': 'project-blurb'})]
标签:python,python-3-x,beautifulsoup,python-3-5