簡體   English   中英

如何使用 bs4 打印 div 的文本

[英]How do I print the text of a div using bs4

我正在抓取coinmarketcap ,我正在嘗試獲取位於主頁底部的硬幣名稱。 使用這一行crypto_name = crypto_details.find("p", class_="sc-1eb5slv-0 iworPT")它打印我[<p class="sc-1eb5slv-0 iworPT" color="text" font-size="1" font-weight="semibold">Bitcoin</p>]這就是我想要的。 但是當我print(crypto_name.string.strip())只有硬幣的名稱時,我得到'NoneType' object 沒有屬性'text'。

我也嘗試了 .get_text 和 .string 但得到了相同的結果。 我也嘗試用 find_all() 替換 find() 但這顯然不起作用,因為只有一個 p。 我還嘗試刪除名稱的第一個和最后一個字符以擺脫 [ ] 但這也不能解決問題。 我如何讓它顯示硬幣的名稱,為什么會出現這樣的錯誤?

頁面加載正確(我使用 selenium 這樣做)

完整代碼:

chrome_options = Options()
chrome_options.add_argument("--headless")

URL = "https://coinmarketcap.com/"
driver = webdriver.Chrome(
    service=Service(ChromeDriverManager().install()), options=chrome_options
)
driver.get(URL)

soup = BeautifulSoup(driver.page_source, "html.parser")
results = soup.find("div", class_="grid")
crypto_detail = results.find_all("tr")
for crypto_details in crypto_detail:
    crypto_name = crypto_details.find("p", class_="sc-1eb5slv-0 iworPT")
    print(crypto_name.text.strip())
    sleep(randint(2, 10))

嘿,我設法通過僅使用文本來取回文本,這就是我所做的

crypto_detail = soup.find_all('p', {'class': 'sc-1eb5slv-0 iworPT'})
#grabs all the paragraph tags that has the class your looking for
for crypto_details in crypto_detail:
    name = crypto_details.text.strip()
    print(name)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM