【问题标题】:Python Scraping Error - You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()? [duplicate]Python Scraping Error - 您可能将元素列表视为单个元素。当您打算调用 find() 时,您是否调用了 find_all()? [复制]
【发布时间】:2021-10-17 00:29:51
【问题描述】:
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
import requests

user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.``3945.88 Safari/537.37"
url = 'https://emetonline.org/events/past-events/'
data = requests.get(url, headers={'User-Agent': user_agent})
soup = BeautifulSoup(data.text, 'lxml')

events = soup.find_all('div', class_ = 'col-12')
event_name = events.find('h4')  ->here's the error

print(event_name.text)

错误是这样的:

Traceback (most recent call last):
  File "C:\Users\90507\Desktop\adsad.py", line 12, in <module>
    event_name = events.find('h4')
  File "C:\Users\90507\AppData\Local\Programs\Python\Python39\lib\site-packages\bs4\element.py", line 2173, in __getattr__
    raise AttributeError(
AttributeError: ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

我做错了什么?

【问题讨论】:

  • 使用 find_all 时必须循环遍历每个事件
  • 嗯,错误消息显示“ResultSet 对象没有属性'find'。您可能将元素列表视为单个元素。”,您认为这是什么意思?上面写着“当您打算调用 find() 时,您是否调用了 find_all()?”,您是否尝试回答这个问题?你对这个问题的回答是什么?这是否让您对如何更改代码有所了解?当您尝试对代码进行更改时发生了什么? (提示:在上一行中,你认为events 最终会是什么样子?)
  • 如果您不会阅读错误消息,我们为什么要相信您会阅读我们给您的任何答案?
  • 我通过将ResultSet object has no attribute 'find'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()? 复制并粘贴到搜索引擎中找到了链接的重复项。在未来,请至少尝试这么多。在 Stack Overflow 上,您是 expected 尝试自己解决问题,而我实在想不出任何更简单的方法可以尝试。

标签: python python-3.x web-scraping


【解决方案1】:

使用 find_all 时必须循环遍历每个事件

解决方法如下:

from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
import requests

user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.``3945.88 Safari/537.37"
url = 'https://emetonline.org/events/past-events/'
data = requests.get(url, headers={'User-Agent': user_agent})
soup = BeautifulSoup(data.text, 'lxml')

events = soup.find_all('div', class_ = 'col-12')
for event in events:
    event_name = event.find('h4')
    print(event_name.text)

【讨论】:

    猜你喜欢
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多