【问题标题】:soup.find_all returns an empty list regardless of what class I enter (Google Colab)不管我输入什么类,soup.find_all 都会返回一个空列表(Google Colab)
【发布时间】:2022-01-08 21:32:16
【问题描述】:

我知道以前有人问过这个问题,但我找不到任何在 Google colab 中完成的实例(而不是在本地)。我正在尝试使用请求和 BeautifulSoup 从 API 输出中抓取区域名称和相关的纬度和经度。我的代码如下:

#Importing tools
import numpy as np
import pandas as pd

import requests
import string
from bs4 import BeautifulSoup

import os

#Getting the HTML elements from the URL
URL = "http://api.positionstack.com/v1/forward?access_key=4d197793636f1badcdc02c14da0f8da0&query=London&limit=1"
html = requests.get(URL)
soup = BeautifulSoup(html.content, 'html.parser')


#I went onto the website, inspected it and found that the latitudes, longitudes and place names are in the span.n elements
#I'm grabbing this from the website here and viewing it
soup_k = soup.find_all("span", class_="n")

soup_k

但它只是输出: []

我还尝试了使用检查可以找到的所有其他元素,但它们都没有返回任何内容。我看到类似问题的解决方案表明这些元素隐藏在 Javascript 后面,但我认为情况并非如此......

任何关于为什么它返回一个空列表或帮助抓取此页面的想法将不胜感激!谢谢

免责声明:我是编码新手,我已尝试确保我的术语是正确的,并且以正确的方式提出问题,但我仍在学习 - 任何指向正确方向的指针总是受欢迎的

p>

【问题讨论】:

    标签: python web-scraping beautifulsoup findall python-requests-html


    【解决方案1】:

    它不是一个网站,它是一个响应 json 而不是 html 的 API。所以不需要BeautifulSoup,只需抓住json 并选择你的属性:

    import requests
    URL = "http://api.positionstack.com/v1/forward?access_key=4d197793636f1badcdc02c14da0f8da0&query=London&limit=1"
    
    res = requests.get(URL).json()
    

    资源输出:

    {'data': [{'latitude': 51.509648, 'longitude': -0.099076, 'type': 'locality', 'name': 'London', 'number': None, 'postal_code': None, 'street': None, 'confidence': 1, 'region': 'Greater London', 'region_code': None, 'county': None, 'locality': 'London', 'administrative_area': None, 'neighbourhood': None, 'country': 'United Kingdom', 'country_code': 'GBR', 'continent': 'Europe', 'label': 'London, England, United Kingdom'}]}
    

    要访问您的属性:

    lat = res['data'][0]['latitude']
    lng = res['data'][0]['longitude']
    region = res['data'][0]['region']
    
    print(lat,lng,region)
    

    输出:

    51.509648 -0.099076 Greater London
    

    【讨论】:

      【解决方案2】:

      我也遇到过这种情况。 如果将 BS 对象打印为字符串,则可以看到每个 HTML 元素之间都有段落符号。 BS 将这些段落符号识别为元素并将它们解析为空元素。因此,您将检索空元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-14
        • 2021-04-13
        • 2020-11-03
        • 1970-01-01
        • 1970-01-01
        • 2016-10-17
        • 1970-01-01
        • 2023-01-05
        相关资源
        最近更新 更多