【问题标题】:Problem looping over multiple divs using Beautiful Soup使用 Beautiful Soup 循环多个 div 的问题
【发布时间】:2020-04-23 11:58:38
【问题描述】:

下面是我使用 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)

【问题讨论】:

  • 请编辑您的问题并想一个更好的标题。还要正确格式化代码:stackoverflow.com/editing-help
  • 这个标题会让你投下很多反对票。为什么不写一篇描述您的实际问题的文章?

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


【解决方案1】:

这一行会给你一个错误-

name = containers.find_all("a",{"class","business-name"})

因为 containers 是一个列表,而不是可以调用 find_all() 方法的单个元素。

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

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

containers = soup.find_all("div",{"class","v-card"})

【讨论】:

【解决方案2】:
for items in containers: 
    name_soup = containers.find("a",{"class","business-name"})
    print(name_soup)

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

使用items.find(...)

请告诉我如何在 python 中运行分页循环。

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

【讨论】:

  • 它向我显示了这个错误: Traceback (most recent call last): File "bs.py", line 14, in name = containers.find_all("a",{"class" ,"business-name"}) 文件“C:\Users\LEGION\AppData\Local\Programs\Python\Python38-32\lib\site-packages\bs4\element.py”,第 2127 行,在 getattr raise AttributeError( AttributeError: ResultSet object has no attribute 'find_all'。您可能将元素列表视为单个元素。当您打算调用 find() 时是否调用了 find_all()?
  • 再看,你的循环毫无意义。为什么要在 div 集合中找到相同的 div?您需要展示一个最小的 HTML 示例。
猜你喜欢
  • 2019-12-23
  • 2023-03-13
  • 2011-10-09
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
  • 1970-01-01
  • 2014-05-02
相关资源
最近更新 更多