-1
当我运行我的脚本时,我可以看到两个打印语句(如下所示)带来了所需的结果。无法区分两者之间的差异
但是,我的问题是:如果我可以在脚本中使用第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)
列表理解在这里没有任何意义,因为['findAll'](https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.html?highlight=findall#find-all)返回列表,并且您没有对其元素进行任何操作 –
您的listcomp仅生成'findAll()'结果的副本。这完全没有必要。 – SiHa