我已经成功地使用selenium点击了网站上的几个页面,现在我需要BeautifulSoup来解析数据。问题是,由于某种原因,bs4 认为我在上一页,所以我的 find_all
调用都不起作用。下面是我的代码片段。 calendar_search.click()
调用正在加载所需的页面。我做了一个夸张的隐式等待来让页面加载。根据之前的 SO 问答,我设置了下面的 html
和 soup
变量。我加入了另一个隐含的等待措施。当我调用 pretify
时,我可以看到我正在打印 calendar_search.click()
之前所在页面的 html。如何加载当前页面?谢谢。
calendar_search.click()
browser.implicitly_wait(30)
html = browser.page_source
browser.implicitly_wait(30)
soup = bs4.BeautifulSoup(html, 'html.parser')
print(soup.prettify())
编辑:我尝试了显式等待(见下文)并打印了异常,尽管有 1000 秒! Edit2:页面的一部分必须已加载,因为我得到了我制作的 find_all 列表的 x[0] 。然而,我在重现结果时遇到了麻烦。
try:
element = WebDriverWait(browser,
1000).until(EC.presence_of_element_located((By.CLASS_NAME,
'classname')))
print("Page is ready!")
except TimeoutException:
print("Loading took too much time!")
最佳答案
出于某种奇怪的原因,使用 browser.implicitly_wait()
不起作用,但 time.sleep()
效果很好。我刚刚将 browser.implicitly_wait(30) 更改为 time.sleep(30) ,效果非常好。
我用过chrome驱动。不要忘记将 chrome 驱动程序放在工作目录中,以避免找不到驱动程序
错误。
import time
from bs4 import BeautifulSoup
from selenium import webdriver
url = "https://www.southwest.com/flight/"
browser = webdriver.Chrome()
browser.get(url)
departure = browser.find_element_by_id("originAirport_displayed")
destination = browser.find_element_by_id("destinationAirport_displayed")
departure.send_keys("Chicago (Midway), IL - MDW")
destination.send_keys("New Orleans, LA - MSY")
button = browser.find_element_by_id("submitButton")
button.click()
time.sleep(30)
html = browser.page_source
soup = BeautifulSoup(html, "lxml")
print(soup.prettify())
browser.save_screenshot(browser.title + ".JPEG")
browser.close()
browser.quit()
编辑
lxml
解析器比 html
解析器更快。在官方documentation BeautifulSoup
的他们建议使用 lxml
解析器。
关于python - 使用Selenium后如何使用BeautifulSoup导航到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44143365/