【问题标题】:Python3 Beautifulsoup4 extracting text from multiple container siblingsPython3 Beautifulsoup4 从多个容器兄弟中提取文本
【发布时间】:2023-03-13 23:24:02
【问题描述】:

我是 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

任何建议都会有所帮助。我一直在阅读一整天试图弄清楚。

【问题讨论】:

    标签: python-3.x beautifulsoup


    【解决方案1】:

    选项 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")
    

    output.txt

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      相关资源
      最近更新 更多