gpt4 book ai didi

python - 如何使用 Selenium 获取动态 html?

转载 作者:行者123 更新时间:2023-12-05 06:57:57 24 4
gpt4 key购买 nike

我正在尝试用 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通过通用脚本?

要测试的 URL:“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'])

最佳答案

您要查找的元素存在于 iframe 中。您需要先切换到 iframe 才能获取这些元素。

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/']

关于python - 如何使用 Selenium 获取动态 html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64766011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com