我想刮掉Kickstarter.com网站的一个特定部分
我需要项目标题的字符串。网站是结构化的,每个项目都有这一行。
<div class="Project-title">
我的代码看起来是:
#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行设置另一个值而不是零,Python会显示一个错误。
我需要一个清单与本网站的所有项目标题。例如:
发布于 2016-07-25 10:54:28
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和类project-title的所有元素。然后,我们从这些元素中获取标题,并使用它创建一个列表。
希望它有帮助,如果你有任何问题,请不要犹豫。
编辑:上面的代码的问题是,如果我们不为a返回的列表中的每个元素至少获得一个标记findAll的子元素,它就会失败。
如何防止这种情况:
project_titles = [project.findChildren('a')[0].text for project in project_elements if project.findChildren('a')]这将只在project.findChildren('a')作为至少一个元素的情况下创建列表。(if []返回False)
编辑:为了获得元素的描述(类project-blurb),让我们看一下HTML代码。
<p class="project-blurb">
Bagel is a digital tape measure that helps you measure, organize, and analyze any size measurements in a smart way.
</p>这只是project-blurb类的一段。为了获得它们,我们可以使用与获取project_elements相同的方法,或者使用更精简的:
project_desc = [description.text for description in soup.findAll('p', {'class': 'project-blurb'})]发布于 2016-07-25 11:00:31
您想要的所有数据都在css类人员选中的部分中,只需找到带有项目标题类的h6,并从其中的锚标记中提取文本:
soup = BeautifulSoup(thepage,"html.parser")
print [a.text for a in soup.select("section.staff-picks h6.project-title a")]输出:
[u'The Superbook: Turn your smartphone into a laptop for $99', u'Weighitz: Weigh Smarter', u'Omega2: $5 IoT Computer with Wi-Fi, Powered by Linux', u"Bagel: The World's Smartest Tape Measure", u'FireFlies - Truly Wire-Free Earbuds - Music Without Limits!', u'ISOLATE\xae - Switch off your ears!']或者在find_all中使用find
project_titles = soup.find("section",class_="staff-picks").find_all("h6", "project-title")
print([proj.a.text for proj in project_titles])每个h6标记中也只有一个锚标记,因此无论采取什么方法,您都不能以一个以上的方式结束。
https://stackoverflow.com/questions/38564754
复制相似问题