首页 > 解决方案 > 用漂亮的汤(python)按类搜索不起作用

问题描述

我正在尝试从网站https://www.ipma.pt/pt/otempo/prev.localidade.hora/#Porto&Gondomar获取日期以及最低和最高温度。我想找到所有带有日期类的 div 和所有带有 tempMin 和 tempMax 类的跨度,所以我写了

pagina2= "https://www.ipma.pt/pt/otempo/prev.localidade.hora/#Porto&Gondomar"
client2= uReq(pagina2)
pagina2bs= soup(client2.read(), "html.parser")
client2.close()

data = pagina2bs.find_all("div", class_="date")
minT = pagina2bs.find_all("span", class_="tempMin")
maxT = pagina2bs.find_all("span", class_="tempMax")

但我得到的只是空列表。我已经将它与类似的代码进行了比较,我看不出我在哪里犯了错误,因为这些类有明显的标签。

标签: pythonweb-scrapingbeautifulsoup

解决方案


从我的角度来看,它与 pagina2bs 变量的内容有关。您将正确的变量传递给find_all方法。

使用 selenium 获取该网站的 html。

from bs4 import BeautifulSoup as bs
from selenium import webdriver 
from selenium.webdriver.chrome.options import Options
import html5lib
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options, executable_path='C:/Users/**USERNAME**/Desktop/chromedriver.exe')
startUrl = "https://www.ipma.pt/pt/otempo/prev.localidade.hora/#Porto&Gondomar"
driver.get(startUrl)
html = driver.page_source

soup = bs(html,features="html5lib")
divs = soup.find_all("div", class_="date")
print(divs)

安装所有需要的软件包和 selenium chrome 驱动程序。就像我在我的机器上做的那样,在代码中链接到这个 chromedriver。


推荐阅读