使用BeautifulSoup提取标记中的文本

2024-06-29 00:57:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个网站的源代码中使用beauthoulsoup来获取文本。部分源代码如下所示:

        <hr />
        <div class="see-more inline canwrap" itemprop="genre">
            <h4 class="inline">Genres:</h4>
<a href="/genre/Horror?ref_=tt_stry_gnr"
> Horror</a>&nbsp;<span>|</span>
<a href="/genre/Mystery?ref_=tt_stry_gnr"
> Mystery</a>&nbsp;<span>|</span>
<a href="/genre/Thriller?ref_=tt_stry_gnr"
> Thriller</a>
        </div>      

所以我一直在尝试用这些代码提取“恐怖”、“神秘”和“惊悚”:

^{pr2}$

但回报是:

['\n', <h4 class="inline">Genres:</h4>, '\n', <a href="/genre/Horror?
ref_=tt_stry_gnr"> Horror</a>, '\xa0', <span>|</span>, '\n', <a 
href="/genre/Mystery?ref_=tt_stry_gnr"> Mystery</a>, '\xa0', <span>|</span>, 
'\n', <a href="/genre/Thriller?ref_=tt_stry_gnr"> Thriller</a>, '\n']

我对python和webscraping还是个新手,所以我希望能得到所有的帮助。谢谢!在


Tags: divref源代码inlineh4classhrefspan
3条回答

使用直接BeautifulSoup.select()函数将所需元素提取到CSS选择器:

import requests
from bs4 import BeautifulSoup

url1 = 'http://www.imdb.com/title/tt5308322/?ref_=inth_ov_tt'
soup = BeautifulSoup(requests.get(url1).text, 'lxml')
genres = [a.text.strip() for a in soup.select("div[itemprop='genre'] > a")]

print(genres)

输出:

^{pr2}$

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors

试试这个,我在用html.parser. 如果您遇到任何问题,请告诉我们:

 for data in genre1:
     get_a = data.find_all("a")
     text = ""
     for i in get_a:
         text = i.text
         print(text)

我用手机时请检查压痕。在

您可以使用BeautifulSoupget_text()方法ind而不是.contents属性来获得您想要的:


来自get_text() documentation:

如果只需要文档或标记的文本部分,可以使用get_text()方法。它以单个Unicode字符串的形式返回文档中或标记下的所有文本:

markup = '<a href="http://example.com/">\nI linked to <i>example.com</i>\n</a>'
soup = BeautifulSoup(markup)

soup.get_text()
>>> u'\nI linked to example.com\n'
soup.i.get_text()
>>> u'example.com'

您可以指定一个用于将文本位连接在一起的字符串:

^{pr2}$

您可以告诉Beautiful Soup从每一位文本的开头和结尾处去掉空白:

soup.get_text("|", strip=True)
>>> u'I linked to|example.com'

但此时您可能需要使用.stripped_strings生成器,并自己处理文本:

[text for text in soup.stripped_strings]
>>> [u'I linked to', u'example.com']

相关问题 更多 >