首页 > 解决方案 > 如何使用 Beautiful Soup 从特定的 div 类中提取文本?

问题描述

所以基本上我想提取里面的文字

<div class = "examplediv">
example text
</div>

我用了

url='https://sample.com'
headers={"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
data = soup.find("div", {"class":"examplediv"})
clean_data = data.text
print(clean_data)

但它永远不会在终端中返回“无”。

我该怎么办?

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


如果重复相同的类名,请尝试find_all代替,这样您可能只会得到第一个项目。应该为您返回一个项目列表。否则你可能会处理在哪个下加载哪个不会通过模块呈现。您需要在这种情况下使用,或共享,以便我们可以手动检查其他方法。findfind_allclasseventJavaScriptrequestsseleniumurl


推荐阅读