无法区分两者之间的差异

时间:2017-05-09 07:17:21

标签: python web-scraping

当我运行我的脚本时,我可以看到两个打印语句(如下所示)带来了所需的结果。

然而,我的问题是:如果我可以在我的脚本中使用第8行[Title]语句(我的意思是,使用方式)获得结果,那么为什么我应该使用第10行[Name]语句,因为你可以看到在其中使用了for循环。

我看过几个不同的脚本,我在第10行[名称]中使用的方式正在迅速增长。两者之间有什么区别吗?

import requests
from bs4 import BeautifulSoup
url = "https://www.yellowpages.com/search?search_terms=pizza&geo_location_terms=Los+Angeles%2C+CA"
req = requests.get(url)
bsObj = BeautifulSoup(req.text,"lxml")
Items=bsObj.findAll("div",{"class":"info"})
for product in Items:

    Title=product.findAll("a",{"class":"business-name"})[0].text
    print(Title)

    Name=[item for item in product.findAll("a",{"class":"business-name"})][0].text
    print(Name)

1 个答案:

答案 0 :(得分:1)

在第一个语句中,findAll方法返回一个可迭代的,并且您正在选择第一个项([0])。 对于具有列表推导的第二个,您首先创建一个列表,其中包含遍历iterable中的所有元素,然后再次选择第一个元素,这将产生完全相同的结果。

顺便说一下,你仍然可以使用find()方法或find_all(limit=1)而不是扫描整个对象。