【问题标题】:Scraping html, keep getting errors I can't explain抓取html,不断收到我无法解释的错误
【发布时间】:2021-05-12 22:05:33
【问题描述】:

从 Poocoin 刮取硬币/代币的价格。这听起来可能令人难以置信,但我无法完成这项工作。

import re
import requests
from bs4 import BeautifulSoup

token_poo = requests.get("https://poocoin.app/tokens/0x3d29aa78fb558f84112bbc48a84f371147a920c9")
soupb = BeautifulSoup(token_poo.content, 'html.parser')

#print price
price = soupb.find_all('div', class_='mb-1 d-flex flex-column lh-1')
pricebox = price.find('span', class_='text-success').get_text()
#print("Price: " + (pricebox).strip())
print(pricebox)

在使用 find(id=) 时它适用于 bscScan,但 bscScan 价格通常无用。 希望不要太愚蠢的问题, 提前非常感谢

【问题讨论】:

  • 您遇到了什么错误?我使用 Javascript 手动尝试了同样的事情,它似乎有效。
  • 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()? 是一个。当我遵循建议时,它会抛出 AttributeError: 'NoneType' object has no attribute 'find' 我已经阅读了这些内容并稍微移动了代码但无法修复它......你扩展了这个想法了吗?
  • 运行代码,价格变量是一个空列表。你得到的第一个错误可能是查看列表并建议你只使用其中的一个元素,即使它是空的。所以你的 find_all 没有找到任何匹配项
  • 有道理,是的。感谢您的澄清!

标签: python html web-scraping


【解决方案1】:

我用token_poo.textsoupb.prettify() 打印了请求内容,结果发现该元素不存在,因为它是由JavaScript 异步加载的。请求无法处理 JavaScript 动态生成的元素。一个建议是使用 selenium 和 PhantomJS 来获取页面源,然后你可以使用 BeautifulSoup 进行解析。

例子:

from bs4 import BeautifulSoup
from selenium import webdriver

url = "https://poocoin.app/tokens/0x3d29aa78fb558f84112bbc48a84f371147a920c9"
browser = webdriver.PhantomJS()
browser.get(url)
html = browser.page_source
soupb = BeautifulSoup(html, 'html.parser')
#Then try the rest of the code
price = soupb.find_all('div', class_='mb-1 d-flex flex-column lh-1')
pricebox = price.find('span', class_='text-success').get_text()
#print("Price: " + (pricebox).strip())
print(pricebox)

【讨论】:

    猜你喜欢
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2019-06-10
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多