python -beautifulousoup-如何针对n个孩子并打印文字
我正在尝试在
。我在Div class_ ='SC-1RMT1NR-0 SC-1RMT1NR-2 IMYVIY'
中访问第n个孩子(最大获益)'
我设法从“趋势”部分获取数据“最大的获利者”前3个文本项目。
我得到attributeError:'nontype'对象没有属性'p'
from bs4 import BeautifulSoup
import requests
source = requests.get('https://coinmarketcap.com/').text
soup = BeautifulSoup(source, 'lxml')
section = soup.find(class_='sc-1rmt1nr-0 sc-1rmt1nr-2 iMyvIy')
#List the top 3 Gainers
for top_gainers in section.find_all(class_='sc-16r8icm-0 sc-1uagfi2-0 bdEGog sc-1rmt1nr-1 eCWTbV')[1]:
top_gainers = top_gainers.find(class_='sc-1eb5slv-0 iworPT')
top_coins = top_gainers.p.text
print(top_coins)
I'm trying to scrape the "Biggest Gainers" list of coins on https://coinmarketcap.com/
How do I access the nth child (Biggest Gainers) in the div class_ = 'sc-1rmt1nr-0 sc-1rmt1nr-2 iMyvIy'
I managed to get the data from the "Trending" section but having trouble targeting the "Biggest Gainers" top 3 text items.
I get AttributeError: 'NoneType' object has no attribute 'p'
from bs4 import BeautifulSoup
import requests
source = requests.get('https://coinmarketcap.com/').text
soup = BeautifulSoup(source, 'lxml')
section = soup.find(class_='sc-1rmt1nr-0 sc-1rmt1nr-2 iMyvIy')
#List the top 3 Gainers
for top_gainers in section.find_all(class_='sc-16r8icm-0 sc-1uagfi2-0 bdEGog sc-1rmt1nr-1 eCWTbV')[1]:
top_gainers = top_gainers.find(class_='sc-1eb5slv-0 iworPT')
top_coins = top_gainers.p.text
print(top_coins)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会避免使用这些动态的类,而是使用 - :汤包室和组合者首先通过文本找到所需的块,然后使用组合者指定最终元素的关系以从中提取信息。
I would avoid those dynamic classes and instead use -:soup-contains and combinators to first locate desired block via text, then with the combinators specify the relationship of the final elements to extract info from.
如@qharr所述,您应该避免使用与他的方法相似的动态标识符,而选择通过
: - soup-contains()
和该元素的已知文本:提取我使用的文本
spripped_strings
并用键将其划为dict
:示例
输出
As mentioned by @QHarr you should avoid dynamic identifier similar to his approach the selection comes via
:-soup-contains()
and the known text of the element:To extract the texts I used
stripped_strings
and zipped it with the keys to adict
:Example
Output
您可以使用
:type
来找到“最大的获利者”父div
:输出:
You can use
:nth-of-type
to locate the "Biggest Gainers" parentdiv
:Output: