【问题标题】:How to print the text that's inside the a class using BS4?如何使用 BS4 打印类中的文本?
【发布时间】:2021-06-06 15:57:55
【问题描述】:

HTML

<div class="QRiHXd">
    "Some very secret link" <<< This is the content I want to print out / btw is a link
</div>

代码

import requests
import urllib
import bs4

url = 'https://www.reddit.com/' # There is actually another link
url_contents = urllib.request.urlopen(url).read()

soup = bs4.BeautifulSoup(url_contents, "html.parser")
div = soup.find('div', {'class_': 'QRiHXd'})

content = str(div)
print(content)

我需要打印类中的文本,但是当我尝试打印时它返回:“无”,我不知道为什么。

【问题讨论】:

    标签: python html python-3.x beautifulsoup


    【解决方案1】:

    要从标签中获取文本,您可以使用带有标签的.text

    from bs4 import BeautifulSoup
    
    html_doc = """<div class="QRiHXd">Some very secret link</div>"""
    
    soup = BeautifulSoup(html_doc, "html.parser")
    div = soup.find('div', {'class': 'QRiHXd'})
    
    print(div.text) # Some very secret link
    

    【讨论】:

    • File "C:\Users\My PC\Desktop\python 3.9\hw.py", line 13, in &lt;module&gt; print(div.text()) AttributeError: 'NoneType' object has no attribute 'text' 每次打印都会出现这个错误,你知道是什么问题吗?
    • 我只是给了你如何获取文本的参考,使用.text.get_text()
    猜你喜欢
    • 2021-10-20
    • 2013-09-22
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    相关资源
    最近更新 更多