【问题标题】:BeautifulSoup - extracting texts within one classBeautifulSoup - 在一个类中提取文本
【发布时间】:2018-03-08 04:14:16
【问题描述】:

我正在尝试从以下网页中提取文本:

<div class="MYCLASS">Category1: <a id=category1 href="SomeURL" >
Text1 I want</a> &gt; Category2: <a href="SomeURL" >Text2 I want</a></div>

我试过了:

for div in soup.find_all('div', class_='MYCLASS'):
    for url in soup.find_all('a', id='category1'):
        print(url)

它返回了:

    <a href="someURL" id="category1">Text1 I want</a>

所以我把文字分开了……

    for div in soup.find_all('div', class_='MYCLASS'):
        for url in soup.find_all('a', id='category1'):
            category1 = str(url).split('category1">')[1].split('</a>')[0]
            print(category1)

并提取“我想要的Text1”,但仍然错过“我想要的Text2”。任何想法?谢谢。

编辑:

源代码中还有其他,所以如果我从我的代码中删除id=,它将返回所有其他我不需要的文本。例如,

<div class="MYClass"><span class="Class">RandomText.<br>RandomText.<br>
<a href=someURL>RandomTextExtracted.</a><br>

还有,

</div><div class=MYClass>
<a href="SomeURL>RandomTextExtracted</a>

【问题讨论】:

标签: python web-scraping beautifulsoup


【解决方案1】:

由于元素的id 是唯一的,因此您可以使用id="category1" 找到第一个&lt;a&gt; 标签。要查找下一个&lt;a&gt; 标签,可以使用find_next() 方法。

html = '''<div class="MYCLASS">Category1: <a id=category1 href="SomeURL" >Text1 I want</a> &gt; Category2: <a href="SomeURL" >Text2 I want</a></div>'''
soup = BeautifulSoup(html, 'lxml')

a_tag1 = soup.find('a', id='category1')
print(a_tag1)    # or use `a_tag1.text` to get the text
a_tag2 = a_tag1.find_next('a')
print(a_tag2)

输出:

<a href="SomeURL" id="category1">Text1 I want</a>
<a href="SomeURL">Text2 I want</a>

(我已经针对您提供的链接对其进行了测试,并且在那里也可以使用。)

【讨论】:

    【解决方案2】:

    你需要一点你的代码

    from bs4 import BeautifulSoup
    soup = BeautifulSoup("<div class=\"MYCLASS\">Category1: <a id=category1 href=\"SomeURL\" > \
    Text1 I want</a> &gt; Category2: <a href=\"SomeURL\" >Text2 I want</a></div> \
    I","lxml")
    for div in soup.find_all('div', class_='MYCLASS'):
        for url in soup.find_all('a'):
            print(url.text.strip())
    

    删除 'a' 标记的 id 并运行相同的代码。

    如果你需要指定id的文本,你需要知道id。

    ids = [id1,id2]
    for div in soup.find_all('div', class_='MYCLASS'):
        for id in ids:
            for url in soup.find_all('a',id=id):
                print(url.text.strip())
    

    【讨论】:

    • 谢谢@bigbounty。如果还有其他类同名“MYCLASS”怎么办?当我运行您的代码时,它会返回我想要的 Text1 和 Text2,以及我不想要的其他文本。你将如何提取它?谢谢。
    • 你说不要,还想解压!?
    • 对不起,我刚刚在问题中添加了更多信息。因此,还有一些其他类与目标类具有相同的名称MYCLASS。但我要提取的唯一文本来自 Category1 和 Category2。
    • 列出想要的 id。循环遍历想要的 id 并将 id 放入代码中的 id 标记中并运行它
    • 我想从同一个 id id=category1 中提取 2 个文本。但它只会返回 Text1,而不是 Text2。我正在尝试提取 Text1(在 Category1 之后)和 Text2(在 Category2 之后)。
    猜你喜欢
    • 2013-10-31
    • 2011-01-19
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多