【问题标题】:How to turn text stored in a variable to a BeautifulSoup Object in Pyhton如何将存储在变量中的文本转换为 Python 中的 BeautifulSoup 对象
【发布时间】:2021-08-18 13:55:37
【问题描述】:
   for i in range(self.length):
        print(colored('Title', 'green', attrs=['bold']))
        print(self.url.entries[i].title)
        print(colored('Link', 'green', attrs=['bold']))
        print(self.url.entries[i].link)
        print(colored('Description', 'green', attrs=['bold']))
        soup = BeautifulSoup(self.url.entries[i].summary, 'html.parser')
        for s in soup.find_all('p'):
            print(s)

在这段代码中,我需要将存储在 self.url.entries[i].summary 中的所有文本转换为 RSS Feed 中每个描述部分的 BeautifulSoup 对象,以便仅打印

中的部分

标签。但是,我找不到这样做的方法。

其中一个 self.url.entries[i].summary 中存储的文本是:

    <img alt="APTOPIX Haiti Earthquake" src="https://i.cbc.ca/1.6143421.1629203330!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_460/aptopix-haiti-earthquake.jpg" title="People affected by the Saturday" width="460" />                <p>Heavy rain from Tropical Storm Grace forced a temporary halt to the government's response to the deadly earthquake that battered the impoverished Caribbean nation on Saturday. </p>

【问题讨论】:

  • 在做汤之前尝试 str()...不清楚你传递给构造函数的数据类型

标签: python html beautifulsoup rss


【解决方案1】:

你可以这样做。

from bs4 import BeautifulSoup

my_text = ''' <img alt="APTOPIX Haiti Earthquake" src="https://i.cbc.ca/1.6143421.1629203330!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_460/aptopix-haiti-earthquake.jpg" title="People affected by the Saturday" width="460" />                <p>Heavy rain from Tropical Storm Grace forced a temporary halt to the government's response to the deadly earthquake that battered the impoverished Caribbean nation on Saturday. </p>'''

# Creates a beautifulsoup object
soup = BeautifulSoup(my_text, 'lxml')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多