无法使用请求从网页中抓取两个字段

时间:2020-05-18 20:30:23

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

我正在尝试使用请求从此webpage抓取两个字段。我使用了精确的选择器来定位内容,但是由于它们是动态生成的,因此无法在页面源中使用它们。但是,我将选择器用作占位符。我知道如何使用Selenium来捕获这两个字段,但我想知道如何使用请求来捕获它们。

我需要的字段:

enter image description here

我尝试过:

import requests
from bs4 import BeautifulSoup

url = "https://www.namebase.io/domains/unite"

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
    r = s.get(url)
    soup = BeautifulSoup(r.text,"lxml")
    total_bids = soup.select_one("[class='domain-highlights__container'] [class*='text_type_h4']").text
    highest_lockup = soup.select_one("[class='desktop-bid-card__right'] > [class*='text_type_h3']").text
    print(total_bids,highest_lockup)

如何使用请求获取两个字段?

1 个答案:

答案 0 :(得分:2)

数据是通过JavaScript加载的,但是您可以使用requests模块来获取Json数据。

例如:

import requests

url = 'https://www.namebase.io/api/domains/get/unite'
data = requests.get(url).json()

# uncomment this to print all data:
# import json
# print(json.dumps(data, indent=4))

no_bids = len(data['bids'])
highest = float(data['highestStakeAmount'] / 1_000_000)

print('No. bids', no_bids)
print('Highest lockup', highest)

打印:

No. bids 6
Highest lockup 5.0

编辑(Firefox开发人员工具的屏幕截图,我在其中找到了API URL)

enter image description here