python - 如何使用 Python/Beautiful Soup 提取两个不同标签之间的文本?

标签 python beautifulsoup

我正在尝试使用 Python/Beautiful Soup 将链接标题提取到 HTML 页面上两个粗体标记之间。

我要提取的 HTML 片段如下:

<B>Heading Title 1:</B>&nbsp;<a href="link1">Title1</a>&nbsp;
<a href="link2">Title2</a>&nbsp;

&nbsp;

<B>Heading Title 2:</B>&nbsp;<a href="link3">Title3</a>&nbsp;
<a href="link4">Title4</a>&nbsp;
<a href="link5">Title5</a>&nbsp;

...

我特别希望将 Title1 和 Title2(由定界符分隔)连接到类似列表的对象中的一个条目,对于 Title 3、Title 4 和 Title 5 等也是如此。 (我预见到的一个问题是每个标题之间的标题数量设置不相同。)

我尝试过各种方法,包括:

import requests, bs4, csv

res = requests.get('WEBSITE.html')

soup = BeautifulSoup(res.text, 'html.parser')

soupy4 = soup.select('a')

with open('output.csv', 'w') as f:
    writer = csv.writer(f, delimiter=',', lineterminator='\n')
    for line in soupy4:
        if 'common_element_link' in line['href']:
            categories.append(line.next_element)
            writer.writerow([categories])

然而,虽然这会将所有标题写入文件,但它是通过直接附加每个附加标题来实现的,如下所示:

['Title1']
['Title1', 'Title2']
['Title1', 'Title2', 'Title3']
['Title1', 'Title2', 'Title3', 'Title4']
...

理想情况下,我希望此代码执行以下操作:

['Title1', 'Title2']
['Title3', 'Title4', 'Title5']
...

在 python 列表和一般编程方面,我是一个新手,不知道如何继续。对于任何人可能对此提出的任何和所有反馈,我将不胜感激。

谢谢!

最佳答案

您可以将nth-of-type:not 伪类与通用兄弟~ 组合器一起使用。由于 a 标签都是兄弟,我相信,在显示的 html 中,我使用带有 nth-of-type 的 b 标签来拆分 a block 之间的标签。我使用 :not 删除当前的 a sibling 。

from bs4 import BeautifulSoup as bs

html = '''
<B>Heading Title 1:</B>&nbsp;<a href="link1">Title1</a>&nbsp;
<a href="link2">Title2</a>&nbsp;

&nbsp;

<B>Heading Title 2:</B>&nbsp;<a href="link3">Title3</a>&nbsp;
<a href="link4">Title4</a>&nbsp;
<a href="link5">Title5</a>&nbsp;
'''
soup = bs(html, 'lxml')
items = soup.select('b:has(~a)')
length = len(items)
if length == 1:
    row = [item.text for item in soup.select('b ~ a')]
    print(row)
elif length > 1:
    for i in range(1, length + 1):
        row = [item.text for item in soup.select('b:nth-of-type(' + str(i) + ') ~ a:not(b:nth-of-type(' + str(i + 1) + ') ~ a)')]
        print(row)

输出:

enter image description here

关于python - 如何使用 Python/Beautiful Soup 提取两个不同标签之间的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55661367/

相关文章:

python - DoesNotExist 在/accounts/register/站点匹配查询不存在。 ( Django , python )

python - 使用请求和 Beautifulsoup 在页面中查找文本(使用 CSS)

python - 使用 BeautifulSoup 获取属性值

python - 当我通过字典通过类过滤器搜索标签时,无法在 beautifulsoup 中找到标签

python - 迭代元组,获取下一项

python - 字段类型取决于其他字段的类型

python - BeautifulSoup 只获取 td 标签中的 "general"文本,嵌套标签中没有任何内容

python - 将网站表转换为 pandas df(beautifulsoup 无法识别表)

python - 加速beautifulsoup

python - 使用 Python 和 BeautifulSoup 从网页下载 .xls 文件