使用Beautiful Soup遍历多个div的问题

时间:2020-04-23 11:58:38

标签: python python-3.x python-requests

以下是我使用BS4进行抓取的python代码。当我尝试运行循环时,它会打印相同的数据,还请让我知道如何在python中运行分页循环。

import requests
from bs4 import BeautifulSoup as bs

url = 'https://www.yellowpages.com/los-angeles-ca/restaurants'

page = requests.get(url)

soup = bs(page.content,'html.parser')
#print(len(soup))

containers = soup.find_all("div",{"class","v-card"})
#print(containers[0])

name = containers.find_all("a",{"class","business-name"})
print(name[0].get_text())

phone = soup.find_all("div",{"class","phone"})
#print(phone[0].get_text())

add = soup.find_all("p",{"class","adr"})
#print(add[0].get_text())


for items in containers: 
    name_soup = containers.find("a",{"class","business-name"})
    print(name_soup)

2 个答案:

答案 0 :(得分:0)

for items in containers: 
    name_soup = containers.find("a",{"class","business-name"})
    print(name_soup)

您没有使用items变量;您一直在搜索containers

使用items.find(...)

请让我知道如何在python中运行分页循环。

这要广泛得多,并且实际上取决于目标网站。当您单击站点上的(下一页)按钮时,看看有什么变化。通常,它只是一个查询字符串参数(例如?p=3)。然后将其复制到您的GET中。

答案 1 :(得分:0)

此行会给你一个错误-

# samples 400000x3200
# SVD
U,S,VT = svd(samples, full_matrices=False) 

tot_S = sum(S)
var_exp_S = [(i / tot_S) for i in S]
cum_var_exp_S = np.cumsum(var_exp_S)

# PCA
cov_mat = np.cov(samples.T)
eigen_vals, eigen_vecs = np.linalg.eig(cov_mat)
eigen_vals = np.asarray(sorted(eigen_vals,reverse=True))

tot = sum(eigen_vals)
var_exp = [(i / tot) for i in eigen_vals]
cum_var_exp = np.cumsum(var_exp)


num= 3200
plt.figure(figsize=(10,5))
plt.subplot(121)
plt.title('PCA')
plt.step(range(1,num+1),cum_var_exp[:num], where='mid',color='r')
plt.ylabel('share of variance')
plt.xlabel('principal components')
plt.legend()
plt.grid()

plt.subplot(122)
plt.title('SVD')
plt.step(range(1,num+1),cum_var_exp_S[:num], where='mid',color='r')
plt.ylabel('share of variance')
plt.xlabel('principal components')
plt.legend()
plt.grid()

因为容器是一个列表,而不是您可以在其上调用 find_all()方法的单个元素。

您需要循环访问容器,因为它是您在上一行提取的 div 标签的列表。

这是您的上一行,您将在列表中提取所有 div 标签(具有class = v-card)-

name = containers.find_all("a",{"class","business-name"})
相关问题