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



你好,这是我想要从使用BeautifulSoup中获取第一个链接的代码。

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

我想在这里抓住第一篇文章,所以它会是"Trust 钱包现在支持恒星流明,还有 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']

我该怎么做?

目前我能想到的与您的代码一起使用的最简单的解决方案是使用 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'])

您可以评估循环内的情况,并在找到满意的结果时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

类名与类 css 选择器 ( . ( 用于内容部分,然后使用a类型 CSS 选择器descendant combinator以指定子a标签元素。 select_one返回第一个匹配项

soup.select_one('.content a')['href']

法典:

from bs4 import BeautifulSoup as bs
import requests
r = requests.get('https://www.binance.com/en/blog')   
soup = bs(r.content, 'lxml')
link = soup.select_one('.content a')['href']
print('https://www.binance.com' + link)

最新更新