您好,这是我想从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']
我该怎么做?
答案 0 :(得分:0)
您可以评估循环内的情况,并在找到满意结果时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
答案 1 :(得分:0)
目前我认为与您的代码一起使用的最简单的解决方案是使用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']
答案 2 :(得分:0)
尝试(从“阅读更多”按钮中提取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'])
答案 3 :(得分:0)
对内容部分使用带有类css选择器(.
)的类名,然后将descendant combinator
和a
类型的css选择器一起使用以指定子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)