python-3.x - Python3 Beautifulsoup4 从多个容器兄弟中提取文本

我是 python 的新手,我正在尝试使用 beautifulsoup 仅从一组标签中提取文本。第一个标签是“姓名”,第二个标签是“日期”,我可以从姓名或不在一起的日期中获取文本。这是我要抓取的页面的 html 代码

<div class="results">
 <h1>
   Info Records
 </h1>
 <div class="group">
  <a class="name" href="https://" target="_blank">
   Firstname, Lastname
  </a>
  <br/>
  <span class="date">
   8/24/2020: Text info
  </span>
 </div>
 <div class="group">
  <a class="name" href="https://" target="_blank">
   Different Firstname, Different Lastname
  </a>
  <br/>
  <span class="date">
   8/23/2020: Different Text Info
  </span>
 </div>

对于名称,我使用此代码提取名称,并将它们打印到终端以获取日期,我将类名称更改为“日期”

for arrest in soup.find_all('a', {'class': 'name'}):
    name = arrest.text
    print(name)

html 有大约 20 个名字,我只发布了前 2 个的日期。当我尝试同时打印两个类时,它不起作用。

test = soup.find_all("div",  {"class": ["name", "date"]})
print(test)

此外,正在运行的内容不会写入文本文件。理想情况下,我想要完成的是将类似这样的内容添加到输出文件中:

firsname lastname
8/24/2020 Text info
firstname last name
8/23/20920 different text info

任何建议都会有所帮助。我整天都在阅读,试图弄明白。

最佳答案

选项 1:使用 CSS 选择器。

选项 2:使用 zip()

1:

from bs4 import BeautifulSoup

html = """YOUR ABOVE HTML SNIPPET"""

soup = BeautifulSoup(html, "html.parser")

with open("output.txt", "w") as f:
    # select `name` and `date` class
    for tags in soup.select(".name, .date"):
        f.write(tags.text.strip() + "\n")

2:

with open("output.txt", "w") as f:

    for name, date in zip(
        soup.find_all("a", {"class": "name"}), soup.find_all("span", {"class": "date"})
    ):
        f.write(name.text.strip() + "\n")
        f.write(date.text.strip() + "\n")

输出.txt:

Firstname, Lastname
8/24/2020: Text info
Different Firstname, Different Lastname
8/23/2020: Different Text Info

https://stackoverflow.com/questions/63587502/

相关文章:

reactjs - React 的 Profiler API 上的 startTime 是什么意思?

c++ - leveldb 是否每 4KB 或 2KB 数据 block 生成 Bloom Filt

ios - 我可以声明应用范围内的首字母缩写词替代画外音吗?

python - 从数据框创建字典,其中多列的元组作为键,另一列作为值

c# - Visual Studio 2019 更新中断发布(不正确的 TLS 版本)

javascript - 在 quill-image-resize-vue 中对齐时出错

node.js - 跟踪 Node.js 程序执行

javascript - 使用javascript强制刷新rss feed

python - Colab - python 代码中的 input() 框太长,所以我需要回滚才能

python - Python中不同数据类型的大小