用Python获取此代码中的第一个链接

2024-09-26 17:39:22 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,这是我想从使用BeautifulSoup抓取第一个链接的代码。你知道吗

查看源:https://www.binance.com/en/blog

我想抓住这里的第一篇文章,所以它将是“信托钱包现在支持恒星流明,4个更多的代币”

我正在尝试使用Python来实现这一点。你知道吗

我用这个代码,但它抓住所有的链接,我只想第一个抓住

with open('binanceblog1.html', 'w') as article:
    before13 = requests.get("https://www.binance.com/en/blog", headers=headers2)    
    data1b = before13.text

    xsoup2 = BeautifulSoup(data1b, "lxml")      
    for div in xsoup2.findAll('div', attrs={'class':'title sc-0 iaymVT'}):
        before_set13 = div.find('a')['href']

我该怎么做?你知道吗


Tags: 代码httpsdivcom链接www文章binance
3条回答

当您发现满意的结果时,您可以评估循环和break中的情况。 你知道吗

for div in xsoup2.findAll('div', attrs={'class':'title sc-62mpio-0 iIymVT'}):
    before_set13 = div.find('a')['href']
    if before_set13 != '/en/blog':
         break
    print('skipping ' + before_set13)
print('grab ' + before_set13)

带有这些更改的代码输出: 你知道吗

skipping /en/blog  
grab /en/blog/317619349105270784/Trust-Wallet-Now-Supports-Stellar-Lumens-4-More-Tokens

目前我能想到的最简单的解决方案是使用break,这是因为findAll

for div in xsoup2.findAll('div', attrs={'class':'title sc-62mpio-0 iIymVT'}):
    before_set13 = div.find('a')['href']
    break

对于第一个元素,可以使用find

before_set13 = soup.find('div', attrs={'class':'title sc-62mpio-0 iIymVT'}).find('a')['href']

尝试(从“阅读更多”按钮中提取href)

import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.binance.com/en/blog')
soup = BeautifulSoup(r.text, "html.parser")
div = soup.find('div', attrs={'class': 'read-btn sc-62mpio-0 iIymVT'})
print(div.find('a')['href'])

相关问题 更多 >

    热门问题