【问题标题】:Beautiful Soup not returning anything美丽的汤不返回任何东西
【发布时间】:2021-05-02 14:42:07
【问题描述】:
您好,我正在尝试使用 Beautiful Soup 从网站上抓取网页并打印事实。这是网站https://fungenerators.com/random/facts/animal/weasel。我试图通过网络抓取事实,尽管它总是最终打印 [] 知道我的代码有什么问题吗??
from urllib.request import urlopen
from bs4 import BeautifulSoup
scrape = "https://fungenerators.com/random/facts/animal/weasel"
request_page = urlopen(scrape)
page_html = request_page.read()
request_page.close()
html_soup = BeautifulSoup(page_html, 'html.parser')
fact = html_soup.find_all('div', class_="wow fadeInUp animated animated")
print(fact)
【问题讨论】:
标签:
python
beautifulsoup
urllib
【解决方案1】:
你的代码有两个问题:
-
您想要的元素位于h2 标签下,而不是div。
-
由于某些数据是动态加载的,因此类名会发生变化,并且会删除“动画”一词的第二次出现。而不是类名是wow fadeInUp animated animated,而是wow fadeInUp animated。
请看下面的例子:
from urllib.request import urlopen
from bs4 import BeautifulSoup
scrape = "https://fungenerators.com/random/facts/animal/weasel"
request_page = urlopen(scrape)
page_html = request_page.read()
request_page.close()
html_soup = BeautifulSoup(page_html, 'html.parser')
fact = html_soup.find_all('h2', class_="wow fadeInUp animated")
print(fact)
(由于只有一个标签,您可能需要考虑使用find() 而不是find_all(),以便使用.text 方法获取文本):
...
fact = html_soup.find('h2', class_="wow fadeInUp animated").text
【解决方案2】:
改用我的代码!!!
import requests
from bs4 import BeautifulSoup
response = requests.get('https://fungenerators.com/random/facts/animal/weasel')
soup = BeautifulSoup(response.content, 'html.parser')
result = soup.select('div.wow.fadeInUp.animated.animated')
print(result[0].text)
结果是:
Random Weasel Fact
或者如果你不想使用 css 选择器,那么你可以这样做:
import requests
from bs4 import BeautifulSoup
response = requests.get('https://fungenerators.com/random/facts/animal/weasel')
soup = BeautifulSoup(response.content, 'html.parser')
result = soup.find_all('h2', class_="wow fadeInUp animated")
print(result[0].text)