【发布时间】:2021-02-15 19:27:54
【问题描述】:
我有以下功能:
def get_info(url):
options = webdriver.ChromeOptions()
options.headless = True
chrome_browser = webdriver.Chrome('./chromedriver', chrome_options=options)
chrome_browser.get(url)
name = chrome_browser.find_element_by_xpath("//h1[contains(@class,'text-center medium-text-left')]").text
winter = WebDriverWait(chrome_browser, 10).until(
EC.presence_of_element_located((By.XPATH, '//*[@id="main-content"]/div[1]/div[1]/div/div[2]/div[5]/div['
'2]/div/div[1]/div[3]/div')))
chrome_browser.quit()
return winter, name
我想从这个网站上的冬/春/夏等图表中获取宽度百分比:https://www.fragrantica.com/perfume/Christian-Dior/Sauvage-Eau-de-Parfum-48100.html
所以我希望这个函数在 HTML 页面上返回香水的名称和冬季行。 季节收视率在网站上加载似乎有点慢,所以我尝试添加等到 HTML 行出现。 当我点击冬季收视率图表上的检查时,我得到了这个元素:
<div style="border-radius: 0.2rem; height: 0.3rem; background: rgb(120, 214, 240); width: 90.3491%; opacity: 1;"></div>
首先,BeautifulSoup 没有找到它,所以我尝试了 Selenium。 Selenium 没有找到它,当使用 WebDriverWait 时,它只会显示这个错误:
Traceback (most recent call last):
File "D:/Fragrance selector/main.py", line 16, in <module>
s = info.get_info('https://www.fragrantica.com/perfume/Christian-Dior/Sauvage-Eau-de-Parfum-48100.html')
File "D:\Fragrance selector\fragrance_info_from_net.py", line 24, in get_info
winter = WebDriverWait(chrome_browser, 10).until(
File "D:\Fragrance selector\venv\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
我真的对这个问题没有想法。我对如何从收视率中获得宽度百分比没有更多的想法。如果你们中的一些人能帮助我解决这个问题,我将不胜感激。
【问题讨论】:
-
也许在浏览器中加载页面,将其保存到文件中,看看是否可以在 BeautifulSoup4 中使用相同的逻辑。这可能就像 XPath 错误一样简单。另外,使用
try ... except语句来尝试您的WebDriverWait,这样您就可以在程序中发生异常时处理它。
标签: python html selenium web-scraping