首页 > 解决方案 > 如何使用 Selenium 获取动态 html?

问题描述

我正在尝试用python开发一个网络爬虫,给定一个网站,分析它的html并搜索所有href标签,但是使用Beautiful Soap之类的库是不可能获得html页面的动态内容的,事实上例如,我正在制作的爬虫还必须发现任何脚本生成的 href。所以我发现了 Selenium 并制作了这个脚本:

driver = webdriver.Chrome()
driver.get(url)
driver.execute_script("return document.body.innerHTML")
time.sleep(15)
html = driver.page_source
print("HTML :", html)
links = []
elements = driver.find_elements_by_tag_name('a')
for elem in elements:
    href = elem.get_attribute("href")
    links.append(href)
return links

但是当我运行它时,我在 html 中找不到我看到的内容,例如使用 Chrome 开发人员工具,所以我的问题是:如何获取页面的整个 html 以及由通用生成的 html脚本?

测试网址:“ https://www.lubecreostorepratolapeligna.it/it/cucine-lube/cucine-moderne/

测试示例:我想获取目录中厨房图像的 href

注意,我不想选择一个元素并等待它,这要归功于 WebDriverWait,因为我正在为任何网站创建通用爬虫,所以我没有要等待或搜索的特定元素,我只想获得动态通用 html 的内容。

如果有更好的图书馆适合我的目的,请告诉我。

更新:我在这里找到了解决我的问题的方法是在 html 中搜索任何 iframe(页面的动态内容)然后导航它们的代码

options = Options()
options.add_argument('--headless')
browser = webdriver.Chrome(options=options)
browser.get(url_to_search_for)
soup = BeautifulSoup(browser.page_source, "html.parser")
browser.close()
        
iframe = []
for x in soup.find_all('iframe'):
    print(x['src'])
    if str in x['src']:
        print('ciao')
        iframe.append(x['src'])
for x in iframe:
    try:
        page = urllib.request.urlopen(x, timeout=20)        
    except HTTPError as e:
        page = e.read()
            
    soup = BeautifulSoup(page, 'html.parser')
    for a in soup.find_all('a', href=True):
        print("HREF IFRAME", a['href'])

标签: pythonhtmlseleniumweb-crawler

解决方案


您正在查看的元素存在于iframe. 您需要切换到iframefirst 才能获取这些元素。

url="https://www.lubecreostorepratolapeligna.it/it/cucine-lube/cucine-moderne/"
driver = webdriver.Chrome()
driver.get(url)
time.sleep(5)
driver.switch_to.frame(driver.find_element_by_css_selector("div.row iframe"))
time.sleep(5)
elements=driver.find_elements_by_css_selector(".ajax_content div.gb_CL_product>a")
links=[]
for elem in elements:
    href = elem.get_attribute("href")
    links.append(href)

print(links)

请注意:-time.sleep()是您应该使用的不好的做法WebDriverWait()

控制台输出:

['https://www.cucinelube.it/it/cucine-moderne/adele-project/', 'https://www.cucinelube.it/it/cucine-moderne/clover/', 'https://www.cucinelube.it/it/cucine-moderne/creativa/', 'https://www.cucinelube.it/it/cucine-moderne/essenza/', 'https://www.cucinelube.it/it/cucine-moderne/gallery/', 'https://www.cucinelube.it/it/cucine-moderne/georgia/', 'https://www.cucinelube.it/it/cucine-moderne/immagina-plus/', 'https://www.cucinelube.it/it/cucine-moderne/luna/', 'https://www.cucinelube.it/it/cucine-moderne/noemi/', 'https://www.cucinelube.it/it/cucine-moderne/oltre/', 'https://www.cucinelube.it/it/cucine-moderne/round/', 'https://www.cucinelube.it/it/cucine-moderne/swing/']

推荐阅读