美丽汤 - 无法通过 CSS 选择器找到子标签



我尝试了这里提到的所有解决方案,但没有一个在我的代码上工作。我的问题是我只想从跨度标签这是h2标签的孩子(而不是h3标签)在这个维基百科页面上的文本(https://fr.wikipedia.org/wiki/Manga)这是我的代码:

import numbers
import urllib.request
from bs4 import BeautifulSoup 
quote_page ='https://fr.wikipedia.org/wiki/Manga#:~:text=Un%20manga%20(%E6%BC%AB%E7%94%BB)%20est%20une,quelle%20que%20soit%20son%20origine.'
page = urllib.request.urlopen(quote_page)
soup = BeautifulSoup(page, 'html.parser')
spans = soup.find_all('h2 > span.mw-heading') 
#not working, results show all spans in h2 AND h3 
for span in spans :
print(span.text)

#div_span = soup.find_all('span', class_="mw-headline") 
#for spans in div_span:
#    print(spans.text) #or string ?
如果今天有人有解决方案,我会感谢他;(注释是工作的,但跨度标签与h3标签在它:/)

你接近你的目标,但在我看来,混合的东西,应该使用select,而与css selectors操作:

soup.select('h2 > span.mw-headline')

这里的另一个问题是类被命名为mw-headline而不是mw-heading

import urllib.request
from bs4 import BeautifulSoup 
quote_page ='https://fr.wikipedia.org/wiki/Manga#:~:text=Un%20manga%20(%E6%BC%AB%E7%94%BB)%20est%20une,quelle%20que%20soit%20son%20origine.'
page = urllib.request.urlopen(quote_page)
soup = BeautifulSoup(page, 'html.parser')
for e in soup.select('h2 > span.mw-headline'):
print(e.text)

输出
Étymologie
Genre et nombre du mot « manga » en français
Histoire des mangas
Caractéristiques du manga
Diffusion
Influence du manga
Produits dérivés
Notes et références
Voir aussi

最新更新