Python BS4 导航多个 HTML 标签

问题描述 投票:0回答:1

免责声明,这是学校作业,不要求完整的解决方案,只是 BS4 部分

'我需要抓取 3 个不同的网站,其中包含我认为的研究论文和作者(贡献者)。我需要从每篇论文中获取作者,看看谁在今年贡献了最多的研究。我进行了大量的谷歌搜索、观看视频和其他帖子来尝试找出答案,但没有成功。我发现的很多内容都是一两个标签,但我找不到任何关于如此深的标签的内容。我已经设法找到标题并在终端中进行长度打印,然后检查网站,对 ptitle 标签执行 ctrl+f 操作,每个标题都生成 1660,所以我至少找到了每篇论文。我发现每个 ptitle > dd > form id > input > value 下都包含作者姓名。我不知道如何深入标签以从每个作者的每个表单 id 标签中提取值。每个标题看起来有 6 位作者。我尝试过的附加标签扩展都产生了错误(抱歉不记得它们是什么)。 HTML 导航目前对我来说非常混乱。感谢任何帮助以更好地理解它。一个站点的 url https://openaccess.thecvf.com/CVPR2021?day=all

如果在漫无目的的过程中以某种方式丢失了。最后的问题是如何逐步遍历多个 html 标签以获取较低的值。'

import requests, bs4


def read_webpage(url):
    # Use requests to access webpage
    webpage = requests.get(url)
    webpage.raise_for_status()

    # Set up BS4 to sift through HTML and retrieve desired data
    soup = bs4.BeautifulSoup(webpage.content, 'html.parser')


    titles = soup.select('dt', {'class' : 'ptitle'})


    print(len(titles))
    # return dictionary once its figured out

# Create a dictionary for each year and call read_webpage to fill dictionary
dict_2021 = read_webpage('https://openaccess.thecvf.com/CVPR2021?day=all')
dict_2022 = read_webpage('https://openaccess.thecvf.com/CVPR2022?day=all')
dict_2023 = read_webpage('https://openaccess.thecvf.com/CVPR2023?day=all')

'是我当前的代码。还没有实现它应该做的任何其他方面。只是希望能够找到作者,然后我将其设置为将它们添加到字典中并计算找到该名称的次数,希望这不会比我在拥有作者后想象的更复杂从网站中提取。'

python beautifulsoup
1个回答
-1
投票

这是一个如何将所有标题+作者加载到 pandas 数据框的示例:

import pandas as pd
import requests
from bs4 import BeautifulSoup

url = "https://openaccess.thecvf.com/CVPR2021?day=all"

soup = BeautifulSoup(requests.get(url).content, "html.parser")

all_data = []
for title in soup.select("dt.ptitle"):
    t = title.get_text(strip=True)
    authors = [a.text for a in title.find_next("dd").select("a")]
    all_data.append((t, authors))

df = pd.DataFrame(all_data, columns=["Title", "Authors"])
print(df)

打印:

                                                                                Title Authors
0               Invertible Denoising Network: A Light Solution for Real Noise Removal [Yang Liu, Zhenyue Qin, Saeed Anwar, Pan Ji, Dongwoo Kim, Sabrina Caldwell, Tom Gedeon]
1       Greedy Hierarchical Variational Autoencoders for Large-Scale Video Prediction [Bohan Wu, Suraj Nair, Roberto Martin-Martin, Li Fei-Fei, Chelsea Finn]
2      Over-the-Air Adversarial Flickering Attacks Against Video Recognition Networks [Roi Pony, Itay Naeh, Shie Mannor]
3 Encoder Fusion Network With Co-Attention Embedding for Referring Image Segmentation [Guang Feng, Zhiwei Hu, Lihe Zhang, Huchuan Lu]

...
© www.soinside.com 2019 - 2024. All rights reserved.