因此,使用下面的代码,我想打开一个公寓网站 URL 并抓取网页。
唯一的问题是 Beautiful Soup 不会等到整个网页渲染完毕。
公寓在加载到页面上之前不会在 html 中呈现,这需要几秒钟的时间。我该如何解决?
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://xxxxx.com/properties/?sort=latest'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
containers = page_soup.findAll("div",{"class":"grid-item"})
#len(containers) is empty since the contents haven't been loaded yet!
如果您想等待页面完全加载其数据,您应该考虑使用 selenium,在您的情况下,它可能如下所示:
from bs4 import BeautifulSoup
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
url = "<URL>"
chrome_options = Options()
chrome_options.add_argument("--headless") # Opens the browser up in background
with Chrome(options=chrome_options) as browser:
browser.get(url)
html = browser.page_source
page_soup = BeautifulSoup(html, 'html.parser')
containers = page_soup.findAll("div",{"class":"grid-item"})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)