【问题标题】:Best way to scrape data in Python from this website?从这个网站上用 Python 抓取数据的最佳方法是什么?
【发布时间】:2020-07-18 17:25:50
【问题描述】:

我正在尝试使用以下 Python 脚本从下面的链接中获取硬币的价格,但是我遇到了一些问题。如果你能确定我哪里出错了,那就太好了!

来自各种网站的各种硬币的 URL 存储在名为硬币的 Python 字典中。尝试,除非,如果堆栈用于找到适当的方法来获取价格。出于某种原因,我无法从以下 URL 中提取价格:

https://www.hattongardenmetals.com/buy/2020-gold-britannia-2

正在使用的脚本是:

    for coin in prices:
    response = requests.get(prices[coin]["url"])
    soup = BeautifulSoup(response.text, 'html.parser')

    try:
        text_price = soup.find(
            'td', {'id': 'price-inc-vat-per-unit-1'}).get_text()        
    except:
        text_price = soup.find(
            'td', {'id': 'total-price-inc-vat-1'}).get_text()            
    else:
        text_price = soup.find(
            'span', {'class': 'woocommerce-Price-amount amount'}).get_text       #<------

由于某种原因,箭头突出显示的行不断出现此错误:

AttributeError: 'NoneType' object has no attribute 'get_text'

我该如何解决这个问题以及如何与提供的代码集成?

【问题讨论】:

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


【解决方案1】:

价格在&lt;span&gt;标签内,带有class="h2 d-block":

import requests
from bs4 import BeautifulSoup


url = 'https://www.hattongardenmetals.com/buy/2020-gold-britannia-2'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

print( soup.select_one('span.h2').text )

打印:

£1584.31

【讨论】:

  • 如何在我上面的问题中的代码中实现这一点?
【解决方案2】:

尝试在 get_text 之后加上括号 .. text_price = soup.find('span', {'class': 'woocommerce-Price-amount amount'}).get_text()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-30
    • 2019-11-18
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多