如何使用<p> <span> BeautifulSoup和Python3.x打印或提取div类中的文本?



假设我在div类中有一个类似<div class="col span-3">Name</div>的文本。我试过了,但没能成功。我需要提取类col span-9中的名称后跟文本。这是我的密码。

import requests
from bs4 import BeautifulSoup
url = "https://v2.sherpa.ac.uk/id/publisher/1939?template=romeo"
r = requests.get(url)
htmlContent = r.content
soup = BeautifulSoup(htmlContent, 'html.parser')
title = soup.title
print(title)
div_text = soup.find("div", {"class": "col span-3"}).get_text()
div_text = soup.find("div", {"class": "col span-9"}).get_text()
print(div_text)

当我使用div_text = soup.find("div", {"class": "col span-3"})print(div_text)时,我会给出带有所有标签的结果。但当我使用.get_text((时,它只给出第一个标签名称。当我同时使用col span-3和col span-9来获取文本时,它会给出具有类span-9的文本。

它只给出了一个结果;1066 Tidsskrift for historie[英语]";而不是标题,结果来自col span-9类。我需要这样的";名称:1066 Tidsskrift for historie[英文];网址:http://www.universitypress.dk/shop/1066-tidsskrift-for-73c1.html;国家:丹麦;出版数量:1〃;

第二次赋值时,您正在覆盖div_text。试试这样的东西:

div_text_header = soup.find("div", {"class": "col span-3"}).get_text()
div_text_value = soup.find("div", {"class": "col span-9"}).get_text()
print(div_text_header)
print(div_text_value)

对于您需要的实际数据,您可以这样做:

print(f'{div_text_header}: {div_text_value}')

看起来你正试图为所有数据获取这些信息。这应该有效:

div_headers = soup.find_all("div", {"class": "col span-3"})
div_values = soup.find_all("div", {"class": "col span-9"})
for header, value in zip(div_headers, div_values):
print(f'{header.get_text()}: {value.get_text()}')

最新更新